Why does _ destroy at the end of statement?

此生再无相见时 提交于 2019-12-05 04:11:58

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

The only reason that you'd use let _ = foo() is when the function requires that you use its result, and you know that you don't need it. Otherwise, this:

let _ = foo();

is exactly the same as this:

foo();

For example, suppose foo has a signature like this:

fn foo() -> Result<String, ()>;

You will get a warning if you don't use the result, because Result has the #[must_use] attribute. Destructuring and ignoring the result immediately is a concise way of avoiding this warning in cases where you know it's ok, without introducing a new variable that lasts for the full scope.

If you didn't pattern match against the result then the value would be dropped as soon as the foo function returns. It seems reasonable that Rust would behave the same regardless of whether you explicitly said you don't want it or just didn't use it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!