From 7cf3fb61869cd6e30798c35626f084c2d00bc610 Mon Sep 17 00:00:00 2001 From: keijack Date: Thu, 12 Jan 2023 10:47:37 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=B5=8C=E5=A5=97=E6=A8=A1?= =?UTF-8?q?=E5=9D=97=E8=AF=B4=E6=98=8E=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/basic/crate-module/module.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/basic/crate-module/module.md b/src/basic/crate-module/module.md index 2bbc907b..9b67e0d0 100644 --- a/src/basic/crate-module/module.md +++ b/src/basic/crate-module/module.md @@ -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)。 \ No newline at end of file