3.5 `use`、`super`、`self`
05-
use、super、self — Comprehensive Rust1分钟内可阅读完
译文 · 基于 Comprehensive Rust
原文链接: https://google.github.io/comprehensive-rust/modules/paths.html
3.5 use、super、self
模块可以用 use 把另一个模块中的符号引入作用域。每个模块顶部通常会看到类似这样的写法:
| |
路径
路径按如下方式解析:
作为相对路径:
foo或self::foo指当前模块中的foo,super::foo指父模块中的foo。
作为绝对路径:
crate::foo指当前 crate 根中的foo,bar::foo指barcrate 中的foo。
常见做法是在更短的路径上「再导出」(re-export)符号。例如,crate 顶层的
lib.rs可能写成:
1 2 3 4 5 6 7// Copyright 2022 Google LLC // SPDX-License-Identifier: Apache-2.0 # mod storage; pub use storage::disk::DiskStorage; pub use storage::network::NetworkStorage;这样其他 crate 就能用方便、简短的路径使用
DiskStorage和NetworkStorage。大体上,只有出现在模块中的项才需要
use。但要调用某个 trait 上的方法,该 trait 必须在作用域中——即便已实现该 trait 的类型已经在作用域中。例如,要对实现了Readtrait 的类型调用read_to_string,需要use std::io::Read。
use语句可以使用通配符:use std::io::*。不鼓励这样做,因为不清楚导入了哪些项,而且这些项可能随时间变化。