为什么_destroy 在语句的末尾? [英] Why does _ destroy at the end of statement?

查看:66
本文介绍了为什么_destroy 在语句的末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了一些其他问题和答案指出let _ = foo() 在语句的末尾而不是在作用域退出处销毁结果,这正是 let _a = foo() 所做的.

我找不到对此的任何官方描述,也找不到此语法的任何基本原理.

我对一些相互交织的事物感兴趣:

  • 官方文档中有没有提到它?
  • 这个选择背后的历史是什么?它是 Rust 的绑定/解构规则的自然后果吗?它是从另一种语言继承的东西吗?或者它有其他来源吗?
  • 是否存在使用显式作用域无法实现此语法地址的用例?

解决方案

这只是 Rust 绑定/解构规则的自然后果吗?

是的.您使用 _ 表示您不关心模式中的值,并且首先不应绑定它.如果一个值从来没有绑定到一个变量,那么就没有什么可以保留这个值,所以它必须被删除.

所有可以使用的地方模式:

  • match 武器
  • 条件if let表达式
  • while let 条件循环
  • for 循环
  • let 语句
  • 功能参数
<块引用>

官方文档中甚至提到过它吗?

使用 _

忽略整个值

值得注意的是 _ 不是 一个有效的标识符,因此您不能将其用作名称:

fn main() {让 _ = 42;println!("{}", _);}

错误:预期表达式,找到保留标识符`_`-->src/main.rs:3:20|3 |println!("{}", _);|^ 预期表达

<块引用>

使用显式作用域实现

我想你本可以走这条路并做出这样的表达,只是徘徊"直到范围结束,但我认为它没有任何价值:

let _ = vec![5];vec![5];//相等的//必须等待作用域结束来清理这些,或者显式调用 `drop`

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

这篇关于为什么_destroy 在语句的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆