03-`use` 声明
use 声明 — Rust By Example
译文 · 基于 Rust By Example
原文链接: https://doc.rust-lang.org/stable/rust-by-example/mod/use.html
use 声明
use 声明可以将一个完整的路径绑定到一个新的名字,从而更容易访问。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
| // 将 `deeply::nested::function` 路径绑定到 `other_function`。
use deeply::nested::function as other_function;
fn function() {
println!("called `function()`");
}
mod deeply {
pub mod nested {
pub fn function() {
println!("called `deeply::nested::function()`")
}
}
}
fn main() {
// 更容易访问 `deeply::nested::funcion`
other_function();
println!("Entering block");
{
// 这和 `use deeply::nested::function as function` 等价。
// 此 `function()` 将遮蔽外部的同名函数。
use deeply::nested::function;
function();
// `use` 绑定拥有局部作用域。在这个例子中,`function()`
// 的遮蔽只存在这个代码块中。
println!("Leaving block");
}
function();
}
|