练习题来自:https://practice-zh.course.rs/crate-module/module.html
建议在命令行下操作完成本节内容,Windows 11/10 首选 Windows 终端,好看,支持渲染中文字体,缺点是功能太少了;其次推荐 mobaxterm,除了难看没别的缺点,功能强大。
1
🌟🌟 根据以下的模块树描述实现模块 front_of_house :
库包的根(src/lib.rs)└── front_of_house├── hosting│ ├── add_to_waitlist│ └── seat_at_table└── serving├── take_order├── serve_order├── take_payment└── complain
和课程里写的那个差不多:
// 填空
// in lib.rsmod front_of_house {mod hosting {fn add_to_waitlist() {}fn seat_at_table() {}}mod serving {fn take_order() {}fn serve_order() {}fn take_payment() {}fn complain() {}}
}
2
🌟🌟 让我们在库包的根中定义一个函数 eat_at_restaurant, 然后在该函数中调用之前创建的函数 eat_at_restaurant
代码如下:
mod front_of_house {pub mod hosting {pub fn add_to_waitlist() {}fn seat_at_table() {}}mod serving {fn take_order() {}fn serve_order() {}fn take_payment() {}fn complain() {}}
}pub fn eat_at_restaurant() {// 使用绝对路径调用crate::front_of_house::hosting::add_to_waitlist();// 使用相对路径调用front_of_house::hosting::add_to_waitlist();
}
3
🌟🌟 我们还可以使用 super 来导入父模块中的项
说实话这里用绝对和相对的区别不是很大。。。
mod front_of_house {pub mod hosting {pub fn add_to_waitlist() {}fn seat_at_table() {}}pub mod serving {fn take_order() {}pub fn serve_order() {}fn take_payment() {}fn complain() {}}
}mod back_of_house {fn fix_incorrect_order() {cook_order();// 使用三种方式填空//1. 使用关键字 `super`//2. 使用绝对路径super::front_of_house::serving::serve_order();crate::front_of_house::serving::serve_order();}fn cook_order() {}
}
4
back_of_house.rs
use super::front_of_house::serving::serving;pub mod back_of_house {use super::serving; pub fn fix_incorrect_order() {cook_order();serving::serve_order();}pub fn cook_order() {}
}
front_of_house
hosting.rs
pub mod hosting {pub fn add_to_waitlist() {}pub fn seat_at_table() -> String {String::from("sit down please")}
}
serving.rs
pub mod serving {pub fn take_order() {}pub fn serve_order() {}pub fn take_payment() {}// 我猜你不希望顾客听到你在抱怨他们,因此让这个函数私有化吧fn complain() {}
}
mod.rs
pub mod hosting;
pub mod serving;
lib.rs
mod front_of_house;
mod back_of_house;pub use crate::front_of_house::hosting::hosting;pub fn eat_at_restaurant() -> String {hosting::add_to_waitlist();back_of_house::back_of_house::cook_order();String::from("yummy yummy!")
}
5
现在我们可以从二进制包中发起函数调用了.
use hello_package::{eat_at_restaurant, hosting::seat_at_table};fn main() {assert_eq!(seat_at_table(), "sit down please");assert_eq!(eat_at_restaurant(),"yummy yummy!");
}
还有一件事,如果你使用VS Code的Rust-Analysis插件,不知道如何导入包,直接敲函数即可,插件会自动修改文件最上方导入的代码。