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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With