是 if-let 还是正常的 if 条件更好? [英] Is an if-let or a normal if condition better?

查看:34
本文介绍了是 if-let 还是正常的 if 条件更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

fn foo() -> Option<()> {
     // ...
}

fn bar() -> Option<()> {
    if let None = foo() { // <---- here
        return None;
    }
}

然后我将 if 语句改为:

Then I changed the if-statement to:

if None == foo()

它也有效.

可以用 a == b 代替 if let a = b 吗?

Is it ok to use a == b instead of if let a = b?

推荐答案

回应和扩展 Magnus Hoff 的观点,当我关心匹配的值时,我只使用 if let .在这个例子中,我会使用类似 Option::is_none 进一步强调我不在乎:

Echoing and expanding on Magnus Hoff's point, I only use if let when I care about the value being matched against. In this example, I'd use something like Option::is_none to further highlight that I don't care:

if foo().is_none() { 

这有一个微小的好处,即回避包装 T 以实现 PartialEq 的要求,如 fjh 指出.

This has the tiny benefit of sidestepping the requirement for the wrapped T to implement PartialEq, as fjh points out.

然而,根据我的经验,这种特殊结构很少见,因为通常你想在 Some 情况下做一些事情.一旦你有多个分支,我就会升级到 match 语句.

In my experience however, this particular construct is rarely seen because usually you want to do something in the Some case. Once you have multiple branches, I upgrade to a match statement.

这篇关于是 if-let 还是正常的 if 条件更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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