Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Rust saying my variable is unused?

Tags:

rust

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.

like image 235
lollercoaster Avatar asked Feb 07 '21 23:02

lollercoaster


2 Answers

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.

like image 120
orlp Avatar answered Nov 03 '22 06:11

orlp


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.

like image 42
Konrad Rudolph Avatar answered Nov 03 '22 06:11

Konrad Rudolph