mod front_of_house {pub mod hosting {pub fn add_to_waitlist() {}}}pub use crate::front_of_house::hosting;pub fn eat_at_restaurant() {hosting::add_to_waitlist();hosting::add_to_waitlist();hosting::add_to_waitlist();}
将 front_of_house模块移动到属于它自己的文件 src/front_of_house.rs中,通过改变 crate 根文件,使其包含下例所示的代码。
mod front_of_house;pub use crate::front_of_house::hosting;pub fn eat_at_restaurant() {hosting::add_to_waitlist();hosting::add_to_waitlist();hosting::add_to_waitlist();}
src/front_of_house.rs 会获取 front_of_house 模块的定义内容。
pub mod hosting {pub fn add_to_waitlist() {}}
在 mod front_of_house 后使用分号,而不是代码块,这将告诉 Rust 在另一个与模块同名的文件中加载模块的内容。
继续重构我们例子,将 hosting 模块也提取到其自己的文件中,仅对 src/front_of_house.rs 包含 hosting 模块的声明进行修改:
pub mod hosting;
接着我们创建一个 src/front_of_house 目录和一个包含 hosting 模块定义的 src/front_of_house/hosting.rs 文件:
pub fn add_to_waitlist() {}
模块树依然保持相同,eat_at_restaurant 中的函数调用也无需修改继续保持有效,即便其定义存在于不同的文件中。
