Module

在 Rust 语言圣经中,我们已经深入讲解过模块module,这里就不再赘述,直接开始我们的练习。

之前我们创建了一个 package hello-package,它的目录结构在经过多次修改后,变成了以下模样:

1. .
2. ├── Cargo.toml
3. ├── src
4. │   ├── lib.rs
5. │   └── main.rs

下面,我们来为其中的库包创建一些模块,然后在二进制包中使用这些模块。

  1. 🌟🌟 根据以下的模块树描述实现模块 front_of_house :
1. 库包的根(src/lib.rs)
2. └── front_of_house
3. ├── hosting
4. │   ├── add_to_waitlist
5. │   └── seat_at_table
6. └── serving
7. ├── take_order
8. ├── serve_order
9. ├── take_payment
10. └── complain
1. // 填空
2. // in __.rs

4. mod front_of_house {
5. // 实现此模块
6. }
  1. 🌟🌟 让我们在库包的根中定义一个函数 eat_at_restaurant, 然后在该函数中调用之前创建的函数 eat_at_restaurant
1. // in lib.rs

3. // 填空并修复错误

5. // 提示:你需要通过 `pub` 将一些项标记为公有的,这样模块 `front_of_house` 中的项才能被模块外的项访问
6. mod front_of_house {
7. /* ...snip... */
8. }

10. pub fn eat_at_restaurant() {
11. // 使用绝对路径调用
12. __.add_to_waitlist();

14. // 使用相对路径调用
15. __.add_to_waitlist();
16. }
  1. 🌟🌟 我们还可以使用 super 来导入父模块中的项
1. // in lib.rs

3. mod back_of_house {
4. fn fix_incorrect_order() {
5. cook_order();
6. // 使用三种方式填空
7. //1. 使用关键字 `super`
8. //2. 使用绝对路径
9. __.serve_order();
10. }

12. fn cook_order() {}
13. }

将模块分离并放入独立的文件中

1. #![allow(unused)]
2. fn main() {
3. // in lib.rs
4. pub mod front_of_house {
5. pub mod hosting {
6. pub fn add_to_waitlist() {}

8. pub fn seat_at_table() -> String {
9. String::from("sit down please")
10. }
11. }

13. pub mod serving {
14. pub fn take_order() {}

16. pub fn serve_order() {}

18. pub fn take_payment() {}

20. // 我猜你不希望顾客听到你在抱怨他们,因此让这个函数私有化吧
21. fn complain() {}
22. }
23. }

25. pub fn eat_at_restaurant() -> String {
26. front_of_house::hosting::add_to_waitlist();

28. back_of_house::cook_order();

30. String::from("yummy yummy!")
31. }

33. pub mod back_of_house {
34. pub fn fix_incorrect_order() {
35. cook_order();
36. crate::front_of_house::serving::serve_order();
37. }

39. pub fn cook_order() {}
40. }
41. }
  1. 🌟🌟🌟🌟 请将上面的模块和代码分离到以下目录文件中e :
1. .
2. ├── Cargo.toml
3. ├── src
4. │   ├── back_of_house.rs
5. │   ├── front_of_house
6. │   │   ├── hosting.rs
7. │   │   ├── mod.rs
8. │   │   └── serving.rs
9. │   ├── lib.rs
10. │   └── main.rs
1. // in src/lib.rs

3. // IMPLEMENT...
1. // in src/back_of_house.rs

3. // IMPLEMENT...
1. // in src/front_of_house/mod.rs

3. // IMPLEMENT...
1. // in src/front_of_house/hosting.rs

3. // IMPLEMENT...
1. // in src/front_of_house/serving.rs

3. // IMPLEMENT...

从二进制包中访问库包的代码

请确保你已经完成了第四题,然后再继续进行.

当到底此处时,你的项目结构应该如下所示:

1. .
2. ├── Cargo.toml
3. ├── src
4. │   ├── back_of_house.rs
5. │   ├── front_of_house
6. │   │   ├── hosting.rs
7. │   │   ├── mod.rs
8. │   │   └── serving.rs
9. │   ├── lib.rs
10. │   └── main.rs
  1. 🌟🌟🌟现在我们可以从二进制包中发起函数调用了.
1. // in src/main.rs

3. // 填空并修复错误
4. fn main() {
5. assert_eq!(__, "sit down please");
6. assert_eq!(__,"yummy yummy!");
7. }

你可以在这里找到答案(在 solutions 路径下)