Rust变量绑定-范围和阴影

变量绑定有一个范围,并且被约束在一个块中。块是语句的集合括在大括号 {} 内,所以, 变量阴影 是被允许的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn main() {
// This binding lives in the main function
let long_lived_binding = 1;
// This is a block, and has a smaller scope than the main function
{
// This binding only exists in this block
let short_lived_binding = 2;
println!("inner short: {}", short_lived_binding);
// This binding *shadows* the outer one
let long_lived_binding = 5_f32;
println!("inner long: {}", long_lived_binding);
}
// End of the block
// Error! `short_lived_binding` doesn't exist in this scope
println!("outer short: {}", short_lived_binding);
// FIXME ^ Comment out this line
println!("outer long: {}", long_lived_binding);
}

联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2024

备案号:京ICP备15003423号-3