Rust 的 mod(模块) 说明

模块(Module) 是 Rust 中用来分割和组织代码的基本单元。

怎么在Rust中创建模块?

  1. 使用 mod 关键字创建模块

    直接在代码中用mod创建模块

    复制代码
    mod front_of_house {
     pub mod hosting {
         pub fn add_to_waitlist() {}
     }
    }
  2. 使用单独的文件作为模块

    在该文件中直接写上我们需要的代码,如:

    复制代码
    // 文件 src/front_of_house.rs
         fn take_order() {}
         fn serve_order() {}
         fn take_payment() {}
  3. 使用 mod.rs 文件的目录定义模块

    可以在包含mod.rs的文件目录中来定义模块,并且可以在mod.rs文件中声明和加载当前目录下的子模块,如:

    复制代码
    ├── memory_pools
    ├── config.rs
    ├── fair_pool.rs
    ├── logging_pool.rs
    ├── mod.rs
    ├── task_shared.rs
    └── unified_pool.rs

    mod.rs中的内容如下:

    复制代码
    mod config;
    mod fair_pool;
    pub mod logging_pool;
    mod task_shared;
    mod unified_pool;
    
    use datafusion::execution::memory_pool::{
        FairSpillPool, GreedyMemoryPool, MemoryPool, TrackConsumersPool, UnboundedMemoryPool,
    };
    use fair_pool::CometFairMemoryPool;
    use jni::objects::GlobalRef;
    use once_cell::sync::OnceCell;
    use std::num::NonZeroUsize;
    use std::sync::Arc;
    use unified_pool::CometUnifiedMemoryPool;
    
    pub(crate) use config::*;
    pub(crate) use task_shared::*;

    在以上中声明了子模块 config fair_pool(如果 mod.rs 文件中没有写 mod 子模块;,即使子文件存在,其内容也不会被编译) 等,并且通过pub(crate) use config::*重新导出子模块中的内容,方便外部调用;

    通过 use fair_pool::CometFairMemoryPool 使用 fair_pool模块中的CometFairMemoryPool结构体.
    注意在 Rust 中,所有项(函数、方法、结构体、枚举、模块和常量)默认对父模块都是私有的,如果需要让上级模块访问子模块的内容,通常需要配合 pub 使用,例如 pub mod 子模块;

相关推荐
Zane19941 分钟前
JMM 与 happens-before:一次搞懂 Java 内存模型
java·后端
冻柠檬飞冰走茶6 分钟前
PTA基础编程题目集 7-11 分段计算居民水费(C语言实现)
c语言·开发语言·算法
An_s8 分钟前
Java Spring Boot+vue3文件管理系统
java·开发语言
用户298698530149 分钟前
在线将 Word 文档转换为 TXT 格式:快速免费的方法
人工智能·后端
shepherd11115 分钟前
别再把 MCP 当成大模型的“手脚”:LLM 并不会直接调用 MCP
后端·ai编程·mcp
SimonKing16 分钟前
别再写 setter 了!MapStruct Plus vs MapStruct,谁才是 Bean 转换的真神?
java·后端·程序员
名字还没想好☜17 分钟前
Go for-range 循环变量陷阱:goroutine 里全打印同一个值(Go 1.22 前后差异)
开发语言·后端·golang·go
AI多Agent协作实战派20 分钟前
AI多Agent协作系统实战(二十五):Spring Boot静态资源同步:为什么你改了代码但线上还是旧的?
后端
码栈研说21 分钟前
Go 语言大白话入门 12 - JSON:工作里最常见的数据格式
后端·程序员
达达尼昂21 分钟前
AI Native 工程实践:如何为 Claude 5 设计更有效的上下文
android·人工智能·后端