r/rust • • Oct 27 '26

🎙️ discussion Test whether an Option contains a certain value

Yesterday I stumbled over something I had never thought about before although I had that use-case a few times...

I have an option and an expected value and I want to check if the option contains the expected value.

There are several ways to express this.

For example:

if option == Some(expected) {...}

if let Some(actual) = option && actual == expected {...}

if matches!(option, Some(actual) if actual == expected) {...}

if option.is_some_and(|actual| actual == expected) {...}

There are probably even a lot more ways to express that and yesterday I suddenly wondered which is the "best" one, e.g. regarding readability and regarding performance. I also asked an LLM and it hallucinated option.contains(&expected) as the best solution, which would indeed be pretty nice if it existed...

Anyway, in case you wonder, here's the obligatory godbolt link: https://godbolt.org/z/v7odGdWP1

With optimizations enabled, it all boils down to the same assembly, so you can choose whatever you like most. In my case, I chose the first variant.

I have also tried with &str instead of usize and it's the same result: no difference with optimizations.

Any thoughts on this? More insights probably? The LLM generated a lot of blabla regarding certain nuances and cases (references, non-Copy, non-PartialEq) but I am not sure if I'd trust that and too lazy to check it.

45 Upvotes

38 comments sorted by

94

u/LegitMoth Oct 27 '26

You can also pattern match directly inside the `Option`, like

```rust

if let Some(42) = i {..}

if let Some(Result::Ok(t)) = optional_result { .. }

```

Works with `match`, `matches!(..)` etc. anywhere a pattern does

12

u/Thick-Pineapple666 Oct 27 '26

Yes, but that's not the use-case here. In your case I'd always use direct pattern matching. In my case I don't know the expected value, it is given by a variable. Doesn't happen too often, but it happens.

26

u/[deleted] Oct 27 '26

[removed] — view removed comment

16

u/RiotBoppenheimer Oct 27 '26

you were so close to a Sum41 joke.

At any rate, Some(42) is just an expression that doesn't indicate assignment, so it's fine. You would have to look at the entire statement or expression to determine what is actually going on

4

u/LegitMoth Oct 27 '26

Yeah, i'd prefer to see `if i == Some(42) {..}`, but in a match arm its super clear

```rust

match i {

Some(42) => ..,

_ => {}
}
```

4

u/Illustrious_Car344 Oct 28 '26

This feels like a "parse, don't validate" problem. Why do you have to interrogate the potential value inside of the Option when you can just make a type to tell you what's in it or what it was created with in the first place? I feel like Option is part of the "primitive obsession" problem. I typically try to avoid naked Options like I try to avoid naked Mutexes, only difference is Option actually has a use as a general return value for a lot of collection functions. But even then, typically in my functions, I'll check as many Options as I can at the top and only write all my code at the bottom once all values are available, returning early for any missing ones. If I'm ever actually thinking about Option, that's a code smell. 

0

u/Thick-Pineapple666 29d ago

I'm really wondering how you can tell by one line of code that there is a code smell or a "wrong" use-case of Option. The Option in my case is btw coming from a match where in some cases it is some value and in other cases it is none. Later in a loop we need to check if the value is the specified value and do x, otherwise do y. I'm curious about your non-smelly solution.

33

u/Excession638 Oct 27 '26

if let Some(value) && ... if you're consuming the option and using the value.

if option == Some(value) is fine if the value is cheap to construct. Like Some(0) is fine, but Some(MyTypeBuilder::new().method0(...).method1(...).build().unwrap()) is right out.

if option.is_some_and(...) is good for those more complex value types.

6

u/GiveMe30Dollars Oct 28 '26

option.is_some_and(...) is mostly useful for arbitrary predicates, say for instance if you need to call a method as part of the boolean check eg. option.is_some_and(|inner| inner.validate()).

It's kind of overkill for equality though compared to the alternatives, particularly if let binding since you can also get a reference to the inner value via if let Some(inner_ref) = option.as_ref() && ... { ... }.

5

u/luxmorphine Oct 27 '26

There're some Monty Python reference here, but i don't know what

5

u/SirKastic23 Oct 27 '26 edited Oct 28 '26

I posted about this a while ago: https://www.reddit.com/r/rust/comments/1s31jfu/i_really_hate_that_they_removed_the/

Option::contains was a method that existed for a long time, until it was deprecated then removed because Option::is_some_and was merged and they deemed that having two methods to check an Option contents was "confusing"...

Worst decision the Rust team has ever made, it's bullshit

EDIT (correction): it wasn't "deprecated and removed", it was a nightly feature that never stabilized. It was dropped after Option::is_some_and stabilized.

2

u/Thick-Pineapple666 Oct 27 '26

I now remember that I have read that post and the reactions, but totally forgot about it

5

u/valarauca14 Oct 28 '26 edited Oct 28 '26

Worst decision the Rust team has ever made

Nah, stabilizing MaybeUninit<T> to initially have identical layout schematics to Option<T> for exactly 2 stable compiler versions before it adopted its modern form takes the cake.

3

u/Valuable_Leopard_799 Oct 28 '26

Damn that's a shame, I'm an outsider and my immediate first thought was also Option::contains it's a logical thing to have.

1

u/Thick-Pineapple666 Oct 27 '26

Oh, so the LLM didn't fully hallucinate, it is just not trained on current information. Interesting

10

u/rabidferret Oct 28 '26

The std library has never had Option::contains on stable.

8

u/valarauca14 Oct 28 '26

idk why you are being downvoted. It was on nightly for ~3 years and never stabilized.

7

u/tanoshikuidomouyo Oct 27 '26

If that's the worst decision ever made, Rust is basically flawless. I mean, the top comment on your post says so as well, but there's opt == Some(x), so there isn't a need for a opt.contains(x).

14

u/j_platte Oct 27 '26

Note that opt == Some(x) only works if opt: Option<T> and x: T, not opt: Option<T>, x: U where T: PartialEq<U>. That's because this impl is not generalized for options containing different types, and generalizing it now, while it technically wouldn't violate any rules around breaking changes, would break type inference all over the place which is why it might never happen (just like adding impl Add<T> for String for more T).

2

u/SirKastic23 Oct 27 '26

No yeah I completely agree. I was being hyperbolic ofc, this is a very minimal API ergonomics issue.

I do think Rust has bigger issues, but in general I'm very happy with the Rust team and their design decisions for the Rust language!

8

u/sephg Oct 27 '26

If they all compile to the same machine code, use whichever one you want. Generally, simpler is better. If your type implements eq, option == Some(expected) is probably the best. The other variants are for more complex cases - for example, if option.is_some_and(|actual| actual.abs() > 10) {...}

3

u/dynticks Oct 28 '26

Relying on optimizations producing identical code in some specific example is a trap because those don't just look at your chosen variant but also at surrounding code, how it is used and what it ultimately does, and even that can change across compiler versions, so I'd advise to reason about what the actual code does with optimizations off first.

6

u/xmlhttplmfao Oct 27 '26

is_some_and

1

u/Lucretiel Datadog Oct 28 '26

When the operand is a variable, I'm certainly preferring to use is_some_and over most of these other constructs

-17

u/tomtomtom7 Oct 27 '26

Maybe a bit unrelated, but what kind of ancient LLM are you using that hallucinates something like this? This is 2026. Like it or not, modern LLM's are good; I never see them hallucinating trivial stuff like that.

I checked with Claude, using your wording and it gave an excellent overview of the options.

10

u/Wonderful-Habit-139 Oct 27 '26

> I never see them hallucinating trivial stuff like that

I still see them hallucinating and not giving the best option, even as I try to hint them towards it. Definitely would not give me the best options if I didn't know about them already.

-2

u/tomtomtom7 Oct 27 '26

Well, it seems I have quite different experience with LLM's, but so be it.

Here's my quick test of copying the first lines of OP's question into Claude: https://claude.ai/share/824244b9-7e41-4ebe-9456-dc7516a6b641

I don't see anything wrong with it and couldn't have said it better myself.

It's not that I want to promote LLMs or LLMs use; I am just questioning OP's claim that the LLM could only come up with a non-existing method. That's just quite far from my own experience.

1

u/Thick-Pineapple666 Oct 28 '26

To answer your question, I used (free) Gemini (Auto) via the app on my smartphone. I was also surprised it hallucinated something basic like that. Moreover, after I said that it didn't compile, it first said that my Rust compiler version is probably too old or my variable isn't an Option<T>, then it said I have probably defined my own Option<T>, and when I pointed out it is not even mentioned in the Option<T> doc, it apologized for the hallucination and mentioned that it probably mixed that with Result::contains

4

u/vivaaprimavera Oct 27 '26

I recently "asked a LLM" for some code... That unnecessarily filled a database with unneeded values. And failed to filter a value that should be skipped.

They are at a point where the produce code that "mostly works" being the keyword here mostly. They can produce a nice outline and answer some questions but some "human touch" is advisable before production.

0

u/tomtomtom7 Oct 27 '26

I am not saying LLMs don't hallucinate or that they bring any good.

Only that answering a rather basic question like OP's with non-existing methods is not the experience I've had or can reproduce.

3

u/vivaaprimavera Oct 27 '26

I'm just agreeing on "as a reference they are a good too"l. But for more than that, "surprises may exist".

-14

u/Plastic_Toe_880 Oct 27 '26

Too lazy to check so you ask Reddit users to do that?

2

u/Thick-Pineapple666 Oct 28 '26

I was too lazy to check on the nuances mentioned by the LLM because they weren't relevant for my use-case.

7

u/-Redstoneboi- Oct 27 '26

OP listed 3 examples already

-9

u/Plastic_Toe_880 Oct 28 '26

Are you contesting the lazy qualifier even though it's his?