模块(Module) 是 Rust 中用来分割和组织代码的基本单元。
怎么在Rust中创建模块?
-
使用 mod 关键字创建模块
直接在代码中用
mod创建模块mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } -
使用单独的文件作为模块
在该文件中直接写上我们需要的代码,如:
// 文件 src/front_of_house.rs fn take_order() {} fn serve_order() {} fn take_payment() {} -
使用
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 子模块;