1

In Rust the "_" character says delete this value (for unused variables) which saves memory but I can still print the value of the variable which has an underscore without compiler errors.

I was wondering if the compiler would give me an error if i tried to reference a value of an underscored variable and expected the compiler to give me and error stating the situation.

fn main() {
    let _val :u16 = 65535;
    println!("finished {}",_val);
}

  • 2
    Prefixing a variable name with an underscore does not drop its value. If you used a *lone* underscore like `let _: u16 = ...`, *then* the value would be dropped immediately. Perhaps you've confused the two? – kmdreko Mar 27 '23 at 21:19

1 Answers1

4

The leading underscore just disables the "unused variable" diagnostic. In every other way, the variable will continue to function as normal.

If the variable is actually unused, why not temporarily comment it out? Then it will not be possible to accidentally reference it.

swiftcoder
  • 343
  • 1
  • 7