为什么Rust说我的变量未使用?
这是一个Rust 游乐场链接,但是:
fn main() {
// marking var as mutable
let mut counter = 0;
counter += 1;
counter += 3;
println!("counter: {}", counter);
// "shadowing" a variable: this is allocating mem for new var,
// and replacing the old one after
let myvar = 5;
let myvar = 1000;
println!("myvar: {}", myvar);
}
这给出了警告:
warning: unused variable: `myvar`
--> src/main.rs:19:9
|
19 | let myvar = 5;
| ^^^^^ help: if this is intentional, prefix it with an underscore: `_myvar`
|
= note: `#[warn(unused_variables)]` on by default
warning: 1 warning emitted
我不太明白。我稍后在println宏中使用它。为什么说没用呢?
也许我还不太了解阴影:我认为它有效地为新变量分配空间,在那里写入新值,然后使符号myvar指向该内存。
回答
隐藏变量会使前一个变量无法访问,但不会“覆盖”它或类似的变量。
因此,您的原始定义let myvar = 5;仍然存在,只是在您的第二个定义之后不再可访问myvar。然而,原始文件仍然被编译器跟踪,它理所当然地抱怨你从不使用它。
- To clarify what "inaccessible" means, the identifier `myvar` won't refer to the first variable since its been shadowed, but its *value* is still accessible by other means like via references. See [this example on the playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=aa1b0de6ab9095386266f9d2624436d1).
回答
我稍后在
println宏中使用它。
不,你没有。您正在使用新变量myvar,该变量隐藏了同名的前一个变量。这就是编译器正确抱怨的原因。
要解决此问题,请删除不必要的let myvar = 5;声明。