Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an if-let or a normal if condition better?

Tags:

rust

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?

like image 666
ckybonist Avatar asked May 05 '16 10:05

ckybonist


2 Answers

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.

like image 169
Shepmaster Avatar answered Sep 29 '22 08:09

Shepmaster


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.

like image 27
fjh Avatar answered Sep 29 '22 07:09

fjh