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 子模块;

相关推荐
雾行0x0030 分钟前
粗排:如何在毫秒级筛出值得精排的内容?
后端·架构
D1213831 分钟前
从零用 C++17 写一个 API 网关:线程模型、控制面分离,以及三个真实 Bug
后端
Scene21631 分钟前
AgentScope Java 进阶:2.如何精准定义问题类型与处理“不确定性”?
后端
用户3459668152132 分钟前
在嵌入式 Linux 摄像头上跑 WebRTC:metaRTC 8.0 的 8 个坑与解法
后端
今天早睡35 分钟前
用 State、Reducer 和条件边搭出可控循环
后端
站大爷IP35 分钟前
Python的字符串格式化把我坑惨了,原来f-string和format的区别这么大
后端
雾行0x0039 分钟前
精排:推荐系统如何给内容打分?从多目标预估到分数融合
后端·架构
今天早睡39 分钟前
Checkpointer 和 thread_id 如何让状态跨调用延续
后端
用户4233412461940 分钟前
Redis 缓存穿透、击穿、雪崩,一次性讲清楚
后端
姜鱼问生1 小时前
2G 内存跑 5 个容器频频 OOM?一招 Swap 抢救你的 2核2G 小破服务器
后端