Why does _ destroy at the end of statement?

  • A+
Category:Languages

I've seen a few other questions and answers stating that let _ = foo() destroys the result at the end of the statement rather than at scope exit, which is what let _a = foo() does.

I am unable to find any official description of this, nor any rationale for this syntax.

I'm interested in a few inter-twined things:

  • Is there even a mention of it in the official documentation?
  • What is the history behind this choice? Is it simply natural fall-out from Rust's binding / destructuring rules? Is it something inherited from another language? Or does it have some other origin?
  • Is there some use-case this syntax addresses that could not have been achieved using explicit scoping?

 


Is it simply natural fall-out from Rust's binding / destructuring rules?

Yes. You use _ to indicate that you don't care about a value in a pattern and that it should not be bound in the first place. If a value is never bound to a variable, there's nothing to hold on to the value, so it must be dropped.

All the Places Patterns Can Be Used:

  • match Arms
  • Conditional if let Expressions
  • while let Conditional Loops
  • for Loops
  • let Statements
  • Function Parameters

Is there even a mention of it in the official documentation?

Ignoring an Entire Value with _

Of note is that _ isn't a valid identifier, thus you can't use it as a name:

fn main() {     let _ = 42;     println!("{}", _); } 
error: expected expression, found reserved identifier `_`  --> src/main.rs:3:20   | 3 |     println!("{}", _);   |                    ^ expected expression 

achieved using explicit scoping

I suppose you could have gone this route and made expressions doing this just "hang around" until the scope was over, but I don't see any value to it:

let _ = vec![5];     vec![5]; // Equivalent // Gotta wait for the scope to end to clean these up, or call `drop` explicitly 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: