Reputation: 16533
Here's a Rust playground link, but:
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);
}
This gives the warning:
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
I don't quite understand. I use it later in the println
macro. Why is it saying it is unused?
Perhaps I don't quite understand shadowing yet: I thought it was effectively allocating space for a new variable, writing the new value there, and then making the symbol myvar
point to that memory.
Upvotes: 8
Views: 1110
Reputation: 171
Because you never use it. They are two different variables but with the same name. If you remove the first declaration where you assign 5, nothing changes.
Upvotes: 0
Reputation: 546153
I use it later in the
println
macro.
No you don’t. You are using the new variable myvar
that’s shadowing the previous variable of the same name. That’s why the compiler correctly complains.
To fix this, remove the unnecessary let myvar = 5;
declaration.
Upvotes: 10
Reputation: 117951
Shadowing a variable makes the previous variable inaccessible but it doesn't 'overwrite' it or similar.
So your original definition let myvar = 5;
still exists, it's just not accessible anymore after your second definition myvar
. However the original still is being tracked by the compiler, and it rightfully complains that you never use it.
Upvotes: 15