显示页面讨论过去修订反向链接回到顶部 本页面只读。您可以查看源文件,但不能更改它。如果您觉得这是系统错误,请联系管理员。 # 19. 模块系统 ## 学习目标 - 理解模块(module)的作用。 - 使用 `mod` 声明模块。 - 使用 `pub` 控制可见性。 - 理解模块树和路径。 ## 19.1 为什么需要模块 随着项目变大,把所有代码放在 `main.rs` 或 `lib.rs` 中会变得难以维护。Rust 提供了**模块系统**来组织代码: - 将相关功能分组。 - 控制哪些部分对外可见。 - 避免命名冲突。 ## 19.2 使用 `mod` 声明模块 ```rust mod front_of_house { mod hosting { fn add_to_waitlist() {} fn seat_at_table() {} } mod serving { fn take_order() {} fn serve_order() {} fn take_payment() {} } } ``` 这里 `front_of_house` 是模块,`hosting` 和 `serving` 是它的子模块。 ## 19.3 模块树 如果把 crate 看作一棵树,根模块 `crate` 就是树根: ```text crate └── front_of_house ├── hosting │ ├── add_to_waitlist │ └── seat_at_table └── serving ├── take_order ├── serve_order └── take_payment ``` ## 19.4 路径 访问模块中的项需要指定路径。路径有两种: - **绝对路径**:从 `crate` 开始,例如 `crate::front_of_house::hosting::add_to_waitlist`。 - **相对路径**:从当前模块开始,例如 `front_of_house::hosting::add_to_waitlist`。 ```rust pub fn eat_at_restaurant() { // 绝对路径 crate::front_of_house::hosting::add_to_waitlist(); // 相对路径 front_of_house::hosting::add_to_waitlist(); } ``` ## 19.5 `pub` 控制可见性 默认情况下,模块内的项对父模块是**私有**的。需要对外暴露时加上 `pub`: ```rust 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(); } ``` 注意:父模块中的项无法访问子模块中的私有项,但子模块可以访问祖先模块中的项。 ## 19.6 文件系统与模块 模块不仅可以内联定义,还可以放到单独文件中: ```text src ├── main.rs └── front_of_house.rs ``` 在 `main.rs` 中: ```rust mod front_of_house; pub fn eat_at_restaurant() { front_of_house::hosting::add_to_waitlist(); } ``` 在 `front_of_house.rs` 中: ```rust pub mod hosting; pub fn add_to_waitlist() {} ``` 更复杂的模块还可以放到目录中: ```text src ├── main.rs └── front_of_house ├── mod.rs └── hosting.rs ``` > 从 Rust 2018 起,更推荐使用 `front_of_house.rs` 与 `front_of_house/` 目录并存的结构,而非必须写 `mod.rs`。 ## 19.7 小结 | 关键字 | 作用 | | `mod` | 声明或引用模块 | | `pub` | 使项对外可见 | | `crate::` | 绝对路径,从根模块开始 | | 相对路径 | 从当前模块开始 | ## 19.8 思考题 1. 为什么 `pub mod hosting` 和 `pub fn add_to_waitlist` 都需要加 `pub`? 2. 绝对路径和相对路径分别在什么场景下更方便? 3. 尝试把一个模块拆分到单独文件中。 登录 Detach Close 该主题尚不存在 您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。 rust/模块系统.txt 最后更改: 2026/08/12 23:34由 张叶安 登录