Merge pull request #1125 from keijack/main

增加模块文件夹的嵌套模块说明。
pull/1144/head
Sunface 2 years ago committed by GitHub
commit 1a26a79fe6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -326,6 +326,38 @@ so easy其实跟之前在同一个文件中也没有太大的不同但是
在这里出现了一个新的关键字 `use`,联想到其它章节我们见过的标准库引入 `use std::fmt;`,可以大致猜测,该关键字用来将外部模块中的项引入到当前作用域中来,这样无需冗长的父模块前缀即可调用:`hosting::add_to_waitlist();`,在下节中,我们将对 `use` 进行详细的讲解。
当一个模块子模块也许多的时候,我们也可以通过文件夹的方式来组织我们子模块。
在上述例子中,我们可以创建一个目录 `front_of_house`,然后在文件夹里创建一个 `hosting.rs` 文件,`hosting.rs` 文件现在就剩下:
```rust
pub fn add_to_waitlist() {}
```
现在,我们尝试编译程序,很遗憾,编译器报错:
```
error[E0583]: file not found for module `front_of_house`
--> src/lib.rs:3:1
|
1 | mod front_of_house;
| ^^^^^^^^^^^^^^^^^^
|
= help: to create the module `front_of_house`, create file "src/front_of_house.rs" or "src/front_of_house/mod.rs"
```
是的,如果需要将文件夹作为一个模块,我们需要进行显示指定暴露哪些子模块。按照上述的报错信息,我们有两种方法:
- 在 `front_of_house` 目录里创建一个 `mod.rs`,如果你使用的 `rustc` 版本 `1.30` 之前,这是唯一的方法。
- 在 `front_of_house` 同级目录里创建一个与模块(目录)同名的 rs 文件 `front_of_house.rs`,在新版本里,更建议使用这样的命名方式来避免项目中存在大量同名的 `mod.rs` 文件( Python 点了个 `踩`)。
而无论是上述哪个方式创建的文件,其内容都是一样的,你需要定义你的子模块(子模块名与文件名相同):
```rust
pub mod hosting;
// pub mod serving;
```
## 课后练习
> [Rust By Practice](https://zh.practice.rs/crate-module/module.html),支持代码在线编辑和运行,并提供详细的[习题解答](https://github.com/sunface/rust-by-practice/blob/master/solutions/crate-module/module.md)。
Loading…
Cancel
Save