Which Syntax Is Preferred For Checking If Optionally Is None? 🤔

These both seem to work, but is one more "idiomatic Rust"?

Do you only use "if let" if you actually want to access some variable from your Option?

Screen Shot 2023-04-03 at 12.56.30 PM

if let None = cli.pattern.as_deref() {
    println!("Didn't pass in any optional pattern");
}

if None == cli.pattern.as_deref() {
    println!("Didn't pass in any optional pattern");
}

.is_none()?

3 Likes
if cli.pattern.is_none() {
    println!("Didn't pass in any optional pattern");
}

See the documentation for Option::is_none and Option::as_deref. The call to as_deref isn't needed as is can't possibly change whether the option is None or not (unless it panics etc.).
If is_none wasn't available, I would always go for an explicit match or if let None = opt because you can only compare None via == iff PartialEq is implemented.

1 Like

Re if there were no is_none(): I'd probably recommend matches!(opt, None) because it's a lot less noisy for a single expression than a full match.

4 Likes

Thanks everybody.

if cli.pattern.is_none() { does work as is the shortest of them all. :+1:

Good point on not needing the as_deref and PartialEq.

I this case though I actually realized I do want to handle with the Some and None cases so I'm probably just going to use a regular match expression. :sweat_smile:

2 Likes

I believe clippy recommends is_{none, some} - it's a very handy linter even without any configuration, and you already have it, just run cargo clippy!

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.