- 包 (package): Cargo 的一个功能,它允许你构建、测试和分享 crate。
- crate :一个模块的树形结构,它形成了库 (library) 或二进制项目 (binary)。
- 模块 (module) 和 use : 允许你控制作用域和路径的私有性。
- 项 (item):指放入模块内的事物,比如 结构体、枚举、函数、特性、方法、常量、模块,默认自身和内部都是私有的 (pravite)。
- 路径 (path):一个命名例如结构体、函数或模块等项的方式
Rust 提供了将包分成多个 crate,将 crate 分成模块,以及通过指定绝对或相对路径从一个模块引用另一个模块中定义的项的方式。你可以通过使用 use
语句将路径引入作用域,这样在多次使用时可以使用更短的路径。模块定义的代码默认是私有的,不过可以选择增加 pub
关键字使其定义变为公有。
package
package 是提供一系列功能的一个或者多个 crate。一个 package 包含:
- 一个 Cargo.toml 文件,阐述如何去构建这些 crate
- 至多包含一个 library crate
- 可以包含任意 “多个” binary crate
- 至少包含一个 crate,无论是 library 还是 binary
crate
crate:Rust中的一个编译单元。 crate 可以编译为二进制文件或库文件。默认情况下,
rustc some_file.rs
将从 some_file crate 生成一个二进制文件。可以使用--crate-type=lib
参数来编译成rlib
文件。 crate file:每当调用rustc some_file.rs
成功编译时时,some_file.rs
都将其视为 crate file。 如果some_file.rs
包含mod
声明,则在对它运行编译器之前,会将 mod 块的内容插入到 crate file 中。换句话说,模块不会单独编译,只有 crate 才能编译。
crate 是一个二进制项目 (binary) 或者库 (library)。
crate root 是一个源文件,Rust 编译器以它为起始点,并构成你的 crate 的根模块。
src/main.rs 是 binary crate 的 crate root,而 binary crate 与 package 同名,即主目录的文件名
src/lib.rs 是 library crate 的 crate root,而 library crate 与 package 同名,即主目录的文件名
crate root 将由 Cargo 传递给 rustc
来实际构建库或者二进制项目
crate 与 scope:
- crate 将一个作用域内的相关功能分组到一起,使得该功能可以很方便地在多个项目之间共享。举一个例子,
rand
crate 提供了生成随机数的功能。通过将rand
crate 加入到我们项目的作用域中,我们就可以在自己的项目中使用该功能。rand
crate 提供的所有功能都可以通过该 crate 的名字:rand
进行访问。 - 将一个 crate 的功能保持在其自身的作用域中,可以知晓一些特定的功能是在我们的 crate 中定义的还是在
rand
crate 中定义的,这可以防止潜在的名称冲突。例如,rand
crate 提供了一个名为Rng
的特性(trait)。我们还可以在我们自己的 crate 中定义一个名为Rng
的struct
。因为一个 crate 的功能是在自身的作用域进行命名的,当我们将rand
作为一个依赖,编译器不会混淆Rng
这个名字的指向。在我们的 crate 中,它指向的是我们自己定义的struct Rng
。我们可以通过rand::Rng
这一方式来访问rand
crate 中的 Rng 特性(trait)。
cargo new my-project
命令会创建一个 my-project 文件主目录:
- 目录下面有
Cargo.toml
文件和src/main.rs
文件,意味着它只含有一个名为my-project
的 binary crate。 - 如果一个 package 同时含有 src/main.rs 和 src/lib.rs,则它有两个 crate:一个 binary 和一个 library,且名字都与包相同。
- 通过将文件放在 src/bin 目录下,一个包可以拥有多个 binary crate:
- 使用
cargo build --bins
:src/main.rs 和每个src/bin下的文件都会被编译成一个独立的 binary crate - 使用
cargo run --bin 单个二进制crate名称
:编译和运行单个 binary crate
- 使用
- 为什么只能有一个 library crate?你使用的他人的 crate 公开的公有代码实际上是他人 crate 的 lib crate 公开出来的内容,根据上面第 2 条说明,lib 的 crate 名只有一个,也就是他人在 crate.io 看到的 crate 名。
- 为什么可以有多个 binary crate?因为 binary 不会提供内部的代码接口给其他人,二进制文件只是执行文件而已;多个 binary crate 意味着 src/bin 下每个 rs 文件名对应各自同名的二进制文件。
- 为什么 library 和 binary crate 与 package 同名,它们不会因为名称发生冲突吗?并不会。记住
- main.rs 的目的是生成二进制文件,此 binary 的名称就是 package 名称;
- lib.rs 的目的是公开代码接口给外部调用,这里的外部有两类:让同 package 的 main.rs 调用(或者说 把 main.rs 的代码拆分进 lib.rs),或者发布到 crate.io 之类的平台上,让其他人调用,调用时引入的名称就是 package 名称。
- main.rs 一定要拆分代码进 lib.rs 吗?它们必须共存吗?不是一定共存的,它们可以单独存在。但是一般把 main.rs 看作功能代码实现,把 lib.rs 看作核心代码实现,使用 main.rs + lib.rs 的结构是清晰和通用的,尤其使用 src/bin 多个二进制 crate 需要公有代码的时候。main.rs 可以借助 mod 拆分文件的方式把代码模块化,让那些代码完全只给 binary crate 服务。让lib 和 binary 共存的其他理由:
- 不满足于单元测试,想让 binary crate 集成测试。因为 lib crate 可以做单元和集成测试,而 binary 只能单元测试。
- 产生二进制文件的同时,考虑把一些二进制文件具备或者不具备的功能代码公布,让其他人使用。
- 上面这种情况的另一面:写一个公开功能、让其他人调用的 crate,同时考虑用这些功能产生二进制文件。
- 如何在 src/main.rs 或者 src/bin 下的 rs 文件 调用 src/lib.rs (或者说 library crate)公开的代码?
- 默认已经被引入,使用
crate::公开的功能
即可,或者使用use crate名称::功能
把一部分功能引入作用域。 - 注意由于变量名不允许
-
,引入时需要把-
写成成_
。即在my-project/src/main.rs
中使用use my_project;
即可调用lib.rs
公有代码。 - 有些老的项目代码会看到类似
extern crate my_project; use my_project;
方式引入 crate,这是 2018 版本之前的写法,目前只需要使用use
,或者直接从 crate 名称开始使用。
- 默认已经被引入,使用
- 不管是 lib 还是 bin crate,下面 module 的规则都适用于这两种 crate。
module
mod
定义模块
- 将一个 crate 中的代码进行分组,以提高可读性与重用性,就像用文件夹给文件分组一样:将相关的定义分组到一起,并(通过名称)指出他们为什么相关。程序员可以通过使用这段代码,更加容易地找到他们想要的定义,因为他们可以基于分组来对代码进行导航,而不需要阅读所有的定义。程序员向这段代码中添加一个新的功能时,他们也会知道代码应该放置在何处,可以保持程序的组织性。
- 控制内部代码的私有性,即控制哪些是可以被外部代码使用的 (public),哪些是作为一个内部实现的内容,不能被外部代码使用 (private)。模块相当于划定一条私有性边界 (privacy boundary ):这条界线不允许外部代码了解、调用和依赖被封装的实现细节,所以,如果你希望创建一个私有函数或结构体,你可以将其放入模块。
结构体、枚举、函数、特性、方法、常量、模块 (这些被称为模块的 items ) ,默认自身和内部都是私有的 (pravite),比如模块自己和里面的内容默认私有。
#![allow(unused)]
fn main() {
// 前台是招待顾客的地方
mod front_of_house {
// 店主可以为顾客安排座位
mod hosting {
fn add_to_waitlist() {}
fn seat_at_table() {}
}
// 服务员接受顾客下单和付款
mod serving {
fn take_order() {}
fn server_order() {}
fn take_payment() {}
}
}
}
module tree (模块树)
crate
└── front_of_house
├── hosting
│ ├── add_to_waitlist
│ └── seat_at_table
└── serving
├── take_order
├── serve_order
└── take_payment
引用模块的 item
使用路径的方式在模块树中找到一个项 ( “item” ) 的位置,路径有两种形式:
绝对路径 absolute path :从 “crate 根” 开始,以 crate 名或者字面值(关键字)
crate
开头,类似于在 shell 中使用/
从文件系统根开始。- 相对路径 relative path :从当前模块开始,以
self
、super
或当前模块的标识符开头。
绝对路径和相对路径都后跟一个或多个由双冒号(::
)分割的标识符。
// `front_of_house` 这个模块和里面的内容并不会在 crate 层面公开出去
// 它只对当前 rs 文件下?平级 (sibiling) 的 item 公开,比如 `eat_at_restaurant`
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
// pub 表示将这个 item 公开出去可以让其他人调用
pub fn eat_at_restaurant() {
// Absolute path
crate::front_of_house::hosting::add_to_waitlist();
// Relative path
front_of_house::hosting::add_to_waitlist();
}
fn main() {}
选择哪种路径,取决于你是更倾向于将项的定义代码与使用该项的代码分开来移动 -> 绝对路径,还是一起移动 -> 相对路径。举一个例子,如果我们要将 front_of_house
模块和 eat_at_restaurant
函数一起移动到一个名为 customer_experience
的模块中,我们需要更新 add_to_waitlist
的绝对路径,但是相对路径还是可用的。然而,如果我们要将 eat_at_restaurant
函数单独移到一个名为 dining
的模块中,还是可以使用原本的绝对路径来调用 add_to_waitlist
,但是相对路径必须要更新。我们更倾向于使用绝对路径,因为把代码定义和项调用各自独立地移动是更常见的。
super
引入上级模块
使用 super
开头来构建从父模块开始的相对路径,类似于文件系统中以 ..
开头的语法。
fn serve_order() {}
mod back_of_house {
fn fix_incorrect_order() {
cook_order();
super::serve_order();
}
fn cook_order() {}
}
fn main() {}
比如我们认为 back_of_house
模块和 serve_order
函数之间可能具有某种关联关系,并且,如果我们要重新组织这个 crate 的模块树,需要一起移动它们。因此,我们使用 super
,这样一来,如果这些代码被移动到了其他模块,我们只需要更新很少的代码。
self
引入当前模块
结合 use
使用:
use std::fmt::{self, Formatter} // 表示同时引入 `std::fmt` 和 `std::fmt::Formatter`
也可以在模块内使用,引入当前模块的子模块:
fn function() {
println!("called `function()`");
}
mod cool {
pub fn function() {
println!("called `cool::function()`");
}
}
mod my {
fn function() {
println!("called `my::function()`");
}
mod cool {
pub fn function() {
println!("called `my::cool::function()`");
}
}
pub fn indirect_call() {
// Let's access all the functions named `function` from this scope!
print!("called `my::indirect_call()`, that\n> ");
// The `self` keyword refers to the current module scope - in this case `my`.
// Calling `self::function()` and calling `function()` directly both give
// the same result, because they refer to the same function.
self::function();
function();
// We can also use `self` to access another module inside `my`:
self::cool::function();
// The `super` keyword refers to the parent scope (outside the `my` module).
super::function();
// This will bind to the `cool::function` in the *crate* scope.
// In this case the crate scope is the outermost scope.
{
use crate::cool::function as root_function;
root_function();
}
}
}
fn main() {
my::indirect_call();
}
把模块拆分进文件
随着代码逐渐增加,模块的内容越来越多,事情变得复杂起来,我们可以把模块内部拆分进文件。
// src/lib.rs
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/lib.rs
mod front_of_house; // 声明与 front_of_house 同名的 rs 文件
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
pub mod hosting {
pub fn add_to_waitlist() {}
}
这样就把最外层模块从
lib.rs
中拆分出来了front_of_house 与 hosting 是上下的层级关系,如果 hosting 模块变成了 hosting.rs ,那么 front_of_house 只能变成同名文件夹,而不再是 rs 文件。所以现在把
src/front_of_house.rs
文件保留,内部 hosting 模块部分变成模块声明pub mod hosting;
;创建目录和文件src/front_of_house/hosting.rs
。src/lib.rs
内容不变,因为仍然需要声明front_of_house
模块,把hosting
模块的内容移入src/front_of_house/hosting.rs
同名文件。
最终的文件树:
.
├── Cargo.toml
├── src
│ ├── front_of_house
│ │ └── hosting.rs
│ ├── front_of_house.rs
│ └── lib.rs
相应的代码内容如下:
// src/lib.rs
mod front_of_house; // 声明与 front_of_house 同名的 rs 文件
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
pub mod hosting;
// src/front_of_house/hosting.rs
pub fn add_to_waitlist() {}
可使用 cargo test
的 lib crate demo: multi_lib.tar.gz
.
├── Cargo.lock
├── Cargo.toml
└── src
├── front_of_house
│ └── hosting.rs
├── front_of_house.rs
└── lib.rs
// src/lib.rs
mod front_of_house; // 声明与 front_of_house 同名的 rs 文件
pub use crate::front_of_house::hosting;
pub fn eat_at_restaurant() -> u32 {
hosting::add_to_waitlist()
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(super::eat_at_restaurant(), 0);
}
}
// src/front_of_house.rs
pub mod hosting;
// src/front_of_house/hosting.rs
pub fn add_to_waitlist() -> u32 {
println!("from add_to_waitlist");
0
}
还可以使用 mod.rs
文件做到上面这个例子的效果:
.
├── Cargo.lock
├── Cargo.toml
└── src
├── front_of_house
│ └── mod.rs
└── lib.rs
// src/lib.rs
pub use crate::front_of_house::hosting;
mod front_of_house; // 声明 front_of_house 是个 mod
// 而实际 front_of_house 是一个文件夹,同时里面必须有 mod.rs
// 从而就不需要 src/front_of_house.rs 文件了
#[cfg(test)]
mod tests {
use super::*; // 为了简便没写 eat_at_restaurant 这个函数
#[test]
fn it_works() {
assert_eq!(hosting::add_to_waitlist(), 0);
}
}
// src/front_of_house/mod.rs
// 如果不想把 hosting 模块拆分成文件,直接在这里定义好 hosting 模块和里面的内容
pub mod hosting {
pub fn add_to_waitlist() ->u32 {
0
}
}
或者这样的模式:
.
├── Cargo.lock
├── Cargo.toml
└── src
├── front_of_house
│ ├── hosting.rs
│ └── mod.rs
└── lib.rs
// src/lib.rs
pub use crate::front_of_house::hosting;
mod front_of_house; // 声明 front_of_house 是个 mod
// 而实际 front_of_house 是一个文件夹,同时里面必须有 mod.rs
// 从而就不需要 src/front_of_house.rs 文件了
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(hosting::add_to_waitlist(), 0);
}
}
// src/front_of_house/mod.rs
// 预先定义好 hosting 模块
pub mod hosting;
// src/front_of_house/hosting.rs
// 直接把 mod hosting 里面的代码写入到文件
pub fn add_to_waitlist() -> u32 {
0
}
其他例子:https://doc.rust-lang.org/rust-by-example/mod/split.html
总而言之,模块拆分进文件的思路:
文件名.rs
的 文件名就是模块名,直接在文件里面填充属于这个模块的内容。当然文件名就是模块名的前提 是在它的父级模块用mod ...;
声明好:- front_of_house 的父模块是 crate root,也就是 src/lib.rs 这个文件里面有 front_of_house 的声明
- hosting 的父模块是 front_of_house,要么是在 front_of_house.rs 被声明,要么是在 src/front_of_house/mod.rs 被声明
- front_of_house.rs 等价于 src/front_of_house/mod.rs。
- 前者更直观,因为可以直接辨识 front_of_house 是一个模块,而且同名文件和文件夹里面就是模块的内容;后者更传统,因为需要点进文件夹才能确定这是一个 mod,很多旧项目是这种模式,因为前者是 2018 版本的添加内容。
- 而且后者这种方式还有一个好处,在进行集成测试的时候,tests/front_of_house/mod.rs 不会被
cargo test
测试,所以它可以存放多个集成测试文件都会用到的共享内容。”demo 见集成测试” 。 - 使用前者方式是做不到的,因为每个集成测试文件会被当作其各自的 crate 来对待,这更有助于创建单独的作用域,这种单独的作用域能提供更类似与最终使用者使用 crate 的环境 —— tests/front_of_house.rs 会被单独测试,即便这个文件并没有包含任何测试函数。
通过使用pub
暴露路径pub
关键字来创建公共项:
- 对于 crate root 下的 item:使该 item 公开出去可以让其他人利用 crate 来调用。
- 对于模块:使子模块的内部部分暴露给上级模块。
- 对于结构体:遵循常规,公开结构体时,其内容(字段、方法)全部是私有的,但是可以继续单独使用
pub
来对个内容公开。 - 对于枚举体:公开枚举体时,其成员默认变成公有的。如果枚举成员不是公有的,那么枚举会显得用处不大。
pub mod
“公开模块。”
比如下面的hosting
模块因为pub
关键字而暴露给了上级模块front_of_house,从而上级模块front_of_house和与此平级的 item 都可使用。
但是模块全部内部默认是私有的,它们并不能看到mod front_of_house {
pub mod hosting {
fn add_to_waitlist() {}
}
}
hosting
下的add_to_waitlist
。如果需要把模块的内容公开出去,必须把这部分内容添加上pub
关键字:#to-comfirm#// `front_of_house` 这个模块和里面的内容并不会在 crate 层面公开出去
// 它只对当前 rs 文件下?平级 (sibiling) 的 item 公开,比如 `eat_at_restaurant`
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
// pub 表示将这个 item 公开出去可以让其他人调用
pub fn eat_at_restaurant() {
// Absolute path
crate::front_of_house::hosting::add_to_waitlist();
// Relative path
front_of_house::hosting::add_to_waitlist();
}
fn main() {}
pub struct
“只公开结构体名称”,其方法、字段默认不公开(需要公开则加pub
)。mod back_of_house {
pub struct Breakfast {
// 这里公开了一个字段
pub toast: String,
seasonal_fruit: String,
}
impl Breakfast {
// 这里公开了方法
pub fn summer(toast: &str) -> Breakfast {
Breakfast {
toast: String::from(toast),
seasonal_fruit: String::from("peaches"),
}
}
}
}
pub fn eat_at_restaurant() {
// Order a breakfast in the summer with Rye toast
let mut meal = back_of_house::Breakfast::summer("Rye");
// Change our mind about what bread we'd like
meal.toast = String::from("Wheat");
println!("I'd like {} toast please", meal.toast);
// The next line won't compile if we uncomment it; we're not allowed
// to see or modify the seasonal fruit that comes with the meal
// meal.seasonal_fruit = String::from("blueberries");
}
pub enum
“内部所有成员公开。”mod back_of_house {
pub enum Appetizer {
Soup,
Salad,
}
}
pub fn eat_at_restaurant() {
let order1 = back_of_house::Appetizer::Soup;
let order2 = back_of_house::Appetizer::Salad;
}
pub use 重导出名称
将 item 引入作用域并同时使其可供其他代码引入自己的作用域。re-export// src/lib.rs
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();
}
pub use
做了两件事:
use
把 hosting 作用域引入进来,可以无需通过它的上级模块去访问调用,因此作用域范围内都可使用,这是use
的作用pub
直接公开了crate::front_of_house::hosting
,外部(调用此 crate 时、或者在此 crate 内的其他 rs 文件)可以直接使用 hosting 和 hosting 内部公开的 item,从公有性的角度看,eat_at_restaurant 和 hosting 一样可以使用,而 front_of_house 是私有的,外部不能使用。
当你的代码的内部结构与调用你的代码的程序员的思考领域不同时,重导出会很有用。例如,在这个餐馆的比喻中,经营餐馆的人会想到“前台”和“后台”。但顾客在光顾一家餐馆时,可能不会以这些术语来考虑餐馆的各个部分。使用 pub use
,我们可以使用一种结构编写代码,却将不同的结构形式暴露出来。这样做使我们的库井井有条,方便开发这个库的程序员和调用这个库的程序员之间组织起来。
pub(路径) 在父级/祖级模块导出
parent module:父级模块,指当前所处模块的上一级
ancestor module:祖级模块,指上级模块以上的模块
pub(crate) itemA:导出到当前 crate,当前 crate 的所有 items 都可以根据路径使用 itemA
pub(in crate::ancestor) itemA:导出到 ancestor 模块,可以根据 crate::ancestor::itemA 使用 itemA
pub(super) itemA:导出到上级模块,路径到上级模块时,无需往下即可使用 itemA
pub(self) itemA:等价于 `itemA`,需要根据当前模块是否 pub 才能判断 itemA 是否 pub
可以根据路径使用的意思是:
1. 平级模块之间直接使用,无需 pub 关键字
2. 非平级模块,目标模块必须是 pub 才能被使用内部 items,否则即使目标模块内部 items 是 pub,也无法被使用
pub
完整例子
例子来源:https://doc.rust-lang.org/rust-by-example/mod/struct_visibility.html
// A module named `my_mod`
mod my_mod {
// Items in modules default to private visibility.
fn private_function() {
println!("called `my_mod::private_function()`");
}
// Use the `pub` modifier to override default visibility.
pub fn function() {
println!("called `my_mod::function()`");
}
// Items can access other items in the same module,
// even when private.
pub fn indirect_access() {
print!("called `my_mod::indirect_access()`, that\n> ");
private_function();
}
// Modules can also be nested
pub mod nested {
pub fn function() {
println!("called `my_mod::nested::function()`");
}
#[allow(dead_code)]
fn private_function() {
println!("called `my_mod::nested::private_function()`");
}
// Functions declared using `pub(in path)` syntax are only visible
// within the given path. `path` must be a parent or ancestor module
pub(in crate::my_mod) fn public_function_in_my_mod() {
print!("called `my_mod::nested::public_function_in_my_mod()`, that\n> ");
public_function_in_nested();
}
// Functions declared using `pub(self)` syntax are only visible within
// the current module, which is the same as leaving them private
pub(self) fn public_function_in_nested() {
println!("called `my_mod::nested::public_function_in_nested()`");
}
// Functions declared using `pub(super)` syntax are only visible within
// the parent module
pub(super) fn public_function_in_super_mod() {
println!("called `my_mod::nested::public_function_in_super_mod()`");
}
}
pub fn call_public_function_in_my_mod() {
print!("called `my_mod::call_public_function_in_my_mod()`, that\n> ");
nested::public_function_in_my_mod();
print!("> ");
nested::public_function_in_super_mod();
}
// pub(crate) makes functions visible only within the current crate
pub(crate) fn public_function_in_crate() {
println!("called `my_mod::public_function_in_crate()`");
}
// Nested modules follow the same rules for visibility
mod private_nested {
#[allow(dead_code)]
pub fn function() {
println!("called `my_mod::private_nested::function()`");
}
// Private parent items will still restrict the visibility of a child item,
// even if it is declared as visible within a bigger scope.
#[allow(dead_code)]
pub(crate) fn restricted_function() {
println!("called `my_mod::private_nested::restricted_function()`");
}
}
}
fn function() {
println!("called `function()`");
}
fn main() {
// Modules allow disambiguation between items that have the same name.
function();
my_mod::function();
// Public items, including those inside nested modules, can be
// accessed from outside the parent module.
my_mod::indirect_access();
my_mod::nested::function();
my_mod::call_public_function_in_my_mod();
// pub(crate) items can be called from anywhere in the same crate
my_mod::public_function_in_crate();
// pub(in path) items can only be called from within the module specified
// Error! function `public_function_in_my_mod` is private
// my_mod::nested::public_function_in_my_mod();
// TODO ^ Try uncommenting this line
// Private items of a module cannot be directly accessed, even if
// nested in a public module:
// Error! `private_function` is private
// my_mod::private_function();
// TODO ^ Try uncommenting this line
// Error! `private_function` is private
// my_mod::nested::private_function();
// TODO ^ Try uncommenting this line
// Error! `private_nested` is a private module
// my_mod::private_nested::function();
// TODO ^ Try uncommenting this line
// Error! `private_nested` is a private module
// my_mod::private_nested::restricted_function();
// TODO ^ Try uncommenting this line
}
打印结果:
called `function()`
called `my_mod::function()`
called `my_mod::indirect_access()`, that
> called `my_mod::private_function()`
called `my_mod::nested::function()`
called `my_mod::call_public_function_in_my_mod()`, that
> called `my_mod::nested::public_function_in_my_mod()`, that
> called `my_mod::nested::public_function_in_nested()`
> called `my_mod::nested::public_function_in_super_mod()`
called `my_mod::public_function_in_crate()`
use
将名称引入作用域
use 自己的 crate
在作用域中增加 use
和路径类似于在文件系统中创建软连接(符号连接,symbolic link)。
// src/lib.rs
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
use crate::front_of_house::hosting;
// 上面的 use 和下面的 use 是等价的
// 因为 src/lib.rs 是 crate root,上面的语句类似于绝对引用
// 又因为需要引入的作用域就在当前文件夹,下面的语句类似于相对引用
// use front_of_house::hosting;
pub fn eat_at_restaurant() {
// 引入函数时,指定到父模块,再调用
hosting::add_to_waitlist();
hosting::add_to_waitlist();
hosting::add_to_waitlist();
}
fn main() {}
为什么不使用 use crate::front_of_house::hosting::add_to_waitlist;
来直接把函数引入作用域?因为 add_to_waitlist 函数是外部定义的(这个例子中 add_to_waitlist 和 eat_at_restaurant 并不能直接相互使用,所以是外部的),为了表明这种外部关系,指定父模块来调用函数的方式就很清楚。这是一种惯例。
另一种惯例是 use
引入结构体、枚举和其他 item 时,习惯是指定它们的完整路径,然后直接使用它们。
// 引入结构体、枚举和其他 item 时,指定完整路径
use std::collections::HashMap;
fn main() {
// 直接调用
let mut map = HashMap::new();
map.insert(1, 2);
}
当使用来自不同模块但是相同名称的 item 时,由于 Rust 不允许同一个作用域出现两个相同名称的 item:
要么指定到父级模块:
// 除非模块的子级有相同名称的 item
use std::fmt;
use std::io;
fn function1() -> fmt::Result {
// --snip--
}
fn function2() -> io::Result<()> {
// --snip--
}
要么使用
as
关键字提供新的名称:use std::fmt::Result;
use std::io::Result as IoResult;
fn function1() -> Result {
// --snip--
Ok(())
}
fn function2() -> IoResult<()> {
// --snip--
Ok(())
}
use 外部的 crate
在Cargo.toml 中加入外部 crate 的名称,比如
[dependencies]
rand = "0.8.3"
在项目代码中就已经加载了这个 外部 crate 命名空间,因此对 crate 层面 pub 的 item,直接使用
外部 crate 名::item
(绝对路径),比如rand::thread_rng()
。注意 函数rand::thread_rng()
是通过pub use
重定向出来的,完整的路径是crate::rngs::thread::thread_rng
。将其他 item 引入就要使用
use
了,比如Rng
trait (随机数生成器,提供了 gen_range 方法)未在crate 层面公开出来,所以需要引入作用域:use rand::Rng;
fn main() {
let secret_number = rand::thread_rng().gen_range(1..101);
}
注意:标准库(
std
)对于你的包来说也是外部 crate。因为标准库随 Rust 语言一同分发,无需修改 Cargo.toml 来引入std
,不过需要通过use
将标准库中定义的项引入项目包的作用域中来引用它们,比如我们使用的HashMap
:use std::collections::HashMap;
use 其他的使用方法
整合引入定义于相同 package 或相同模块的 item:使用
{...}
的嵌套 (nested),可以显著减少所需的独立use
语句的数量// 这样写比较啰嗦
use std::cmp::Ordering;
use std::io;
// 这样看起来就清晰很多,把 `::` 看作类似于 `/` 路径的分隔符号
use std::{cmp::Ordering, io};
可以使用
self
关键字来表示嵌套外层的路径本身:use std::io;
use std::io::Write;
// 等价于
use std::io::{self, Write};
通过
*
(glob 运算符) 将所有的公有定义引入作用域:// 将 std::collections 中定义的所有公有项引入当前作用域。
use std::collections::*;
使用 glob 运算符时请多加小心!Glob 会使得我们难以推导作用域中有什么名称和它们是在何处定义的。
glob 运算符经常用于测试模块tests
中,这时会将所有内容引入作用域;我们将在第十一章 “如何编写测试” 部分讲解。
glob 运算符有时也用于 prelude 模式;查看 标准库中的文档 了解这个模式的更多细节。