Rust 组织管理:衙门的规矩
Rust 提供了一套强大的模块系统来组织代码,包括:Packages(包)、Crates(箱)、Modules(模块)和 Paths(路径)。
🏛️ 模块定义 (mod)
使用 mod 关键字定义模块。默认情况下,模块内的东西都是私有的。
mod yamen {
// 默认是私有的,外面访问不到
fn torture() {
println!("上大刑!");
}
// pub 关键字使其公开
pub fn open_court() {
println!("升堂!");
// 内部可以访问私有函数
torture();
}
}
fn main() {
yamen::open_court(); // ✅ 可以访问
// yamen::torture(); // ❌ 报错!私有函数
}
📂 父子模块与路径
- 绝对路径: 从 crate 根开始,以
crate开头。 - 相对路径: 从当前模块开始,使用
self,super。
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
pub fn eat_at_restaurant() {
// 绝对路径
crate::front_of_house::hosting::add_to_waitlist();
// 相对路径
front_of_house::hosting::add_to_waitlist();
}
🚚 use 关键字
使用 use 将路径引入作用域,就不用每次都写全名了。
use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}
📄 分割到不同文件
当模块变大时,应该把它们移动到单独的文件中。
src/lib.rs:
mod front_of_house; // 声明模块,内容在 front_of_house.rs 中寻找