1. mod front_of_house {
    2. pub mod hosting {
    3. pub fn add_to_waitlist() {}
    4. }
    5. }
    6. pub use crate::front_of_house::hosting;
    7. pub fn eat_at_restaurant() {
    8. hosting::add_to_waitlist();
    9. hosting::add_to_waitlist();
    10. hosting::add_to_waitlist();
    11. }

    front_of_house模块移动到属于它自己的文件 src/front_of_house.rs中,通过改变 crate 根文件,使其包含下例所示的代码。

    1. mod front_of_house;
    2. pub use crate::front_of_house::hosting;
    3. pub fn eat_at_restaurant() {
    4. hosting::add_to_waitlist();
    5. hosting::add_to_waitlist();
    6. hosting::add_to_waitlist();
    7. }

    src/front_of_house.rs 会获取 front_of_house 模块的定义内容。

    1. pub mod hosting {
    2. pub fn add_to_waitlist() {}
    3. }

    在 mod front_of_house 后使用分号,而不是代码块,这将告诉 Rust 在另一个与模块同名的文件中加载模块的内容。
    继续重构我们例子,将 hosting 模块也提取到其自己的文件中,仅对 src/front_of_house.rs 包含 hosting 模块的声明进行修改:

    1. pub mod hosting;

    接着我们创建一个 src/front_of_house 目录和一个包含 hosting 模块定义的 src/front_of_house/hosting.rs 文件:

    1. pub fn add_to_waitlist() {}

    模块树依然保持相同,eat_at_restaurant 中的函数调用也无需修改继续保持有效,即便其定义存在于不同的文件中。