use、super、self
一个模块可以使用“use”将另一个模块的符号全部纳入。您通常在每个模块的顶部会看到如下内容:
1. use std::collections::HashSet;
2. use std::process::abort;
路径
路径解析如下:
-
作为相对路径:
-
foo或self::foo是指当前模块中的foo, - “super::foo”是指父模块中的“foo”。
-
作为绝对路径:
-
crate::foo是指当前 crate 的根中的foo, - “bar::foo”是指“bar”crate 中的“foo”。
This slide should take about 8 minutes.
- 通常使用较短的路径来 “重新导出”符号。例如,crate 中的顶层
lib.rs文件可能会
``` 1. mod storage;
- pub use storage::disk::DiskStorage;
- pub use storage::network::NetworkStorage; ```
通过便捷的短路径,使得 DiskStorage 和 NetworkStorage 可供其他 crate 使用。
- 在大多数情况下,只有模块中显示的项才需通过 use 引入。不过,即使实现该 trait 的类型已处于作用域内,如要调用该 trait 的任何方法,仍需将该 trait 引入到作用域内。例如,如需对实现 Read trait 的类型使用 read_to_string 方法,您需要使用 use std::io::Read 引入。
- use 语句可以包含通配符:use std::io::*。但不推荐这种做法,因为不清楚导入了哪些项,并且这些内容可能会随时间而变化。
