如何“阅读"如果让表达式? [英] How to "read" if let expressions?

查看:51
本文介绍了如何“阅读"如果让表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rust 中,您可以使用 if let 而不是 match 来解包并直接使用一个简单的值.

In Rust, you can use if let instead of match when it comes to unwrapping and directly using just a simple value.

所以代替

match opt_val {
    Some(x) => {
        do_something_with(x);
    }
    _ => {}
}

你可以

if let Some(x) = opt_val {
    do_something_with(x);
}

我应该如何阅读处理这段代码?对于match,这很简单:如果opt_valSome(x) matched 然后做... 使用 x".

How should I read or process this code mentally? For match, this is straightforward: "If opt_val is matched by Some(x) then do... with x".

对于 if let 我总觉得这是错误的方式:如果 Some(x) 匹配(?)opt_val,然后执行....".注意这句话中没有let.

For if let I always have the impression that it is the wrong way round: "If Some(x) matches(?) opt_val, then do....". Note that there is no let in this sentence.

这没什么大不了的,但我一直在为此而绊倒.

It is no big deal, but I continue to stumble over this.

我真的很喜欢如果这个 let 绑定成功,那么......";从接受的答案来看,因为我认为它设定了正确的重点.过分专注于模式匹配让我陷入了这个问题";首先.作为参考,讨论了 (ir)refutability 和 let 这里 在 Rust 书中.

I really like "if this let binding succeeds then..." from the accepted answer, as I think it sets the right focus. Concentrating too much on the pattern matching got me into this "problem" in the first place. For reference, (ir)refutability and let is discussed here in the Rust book.

推荐答案

您不应该期望任何编程语言的语法中的关键字直接映射到英语或任何其他自然语言中的单词.

You shouldn't expect the keywords in the syntax of any programming language to map directly to words in English, or any other natural language.

let 表达式总是接受一个模式,它可以让你做这样的事情:

let expressions in Rust always accept a pattern, which lets you do things like:

let foo = (1, (2, 3));
let (a, (b, _)) = foo;

然而,这仅在模式无可辩驳时有效,即它始终匹配.

However, this only works when the pattern is irrefutable, that is it will always match.

if let 扩展它以适应可能不总是匹配的类型.

if let extends this to accommodate types that may not always match.

您的阅读方式很好:如果模式匹配,则...",或如果此 let 绑定成功,则...".

How you are reading it is just fine: "if the pattern matches then...", or "if this let binding succeeds then...".

这篇关于如何“阅读"如果让表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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