【发布时间】:2020-09-13 04:17:33
【问题描述】:
我的意思的那种事情的简单例子:
let x = 10;
if true {
let x = 20;
}
println!("x is {}", x);
这将打印x is 10,而不是x is 20,并给我一个未使用的变量警告,因为if 块中的x 与它外面的x 不同。有没有办法可以对 if 执行类似捕获的操作,以便它实际作用于包含块的 x?
我在这里想象通过重复的let 语句来执行遮蔽是可取的,但如果它只是一个int,这个例子会更简洁。在伪代码中,可能更像是:
let data = get_data_from_user();
let data = initial_processing(data);
let data = further_processing(data);
if some_condition {
let data = conditional_processing(data);
} else {
let data = fallback_processing(data);
}
(也许答案是这是代码异味,我应该将if some_condition 检查移到conditional_processing 函数调用中。)
例如,对可重现示例的一种可能的重写:
let mut x = 10;
if true {
x = 20;
}
我认为这与我的想法相差太大。
可以写
let x = 10;
let mut y = x;
if true {
y = 20;
}
let x = y;
println!("x is {}", x);
所以x 最终成为设置为20 的非可变变量,尽管以引入一次性中间可变变量y 为代价。但是我仍然很好奇是否可以通过让if 块捕获并故意在其外部隐藏一个变量来实现这一点。
【问题讨论】:
标签: rust expression shadowing