For example:
fn foo() -> Option<()> {
// ...
}
fn bar() -> Option<()> {
if let None = foo() { // <---- here
return None;
}
}
Then I changed the if-statement to:
if None == foo()
and it also works.
Is it ok to use a == b
instead of if let a = b
?
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() {
This has the tiny benefit of sidestepping the requirement for the wrapped T
to implement PartialEq
, as fjh points out.
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.
So my questions is: Is it ok using a == b instead of if let a = b?
Yes, that's absolutely fine.
One thing to note, though, is that the former will only compile if you're working on some type Option<T>
where T
implements PartialEq
, while the latter will work regardless. This is because Option<T>
only implements PartialEq
if T
implements PartialEq
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With