Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Option<String> is Some(my_string)

Tags:

rust

I'd like to know what is the most idiomatic way of checking if a q: Option<String> that I have has the value of a particular string that I have in my_string: String. So the most straightforward solution is:

if q.is_some() && q.unwrap() == my_string

Another one I can think of:

if q.unwrap_or_default() == my_string

but this wouldn't work in the corner case of my_string being empty.

Another one:

match q {
  Some(s) if s == my_string => {
    ...
  },
  _ => {},
}

but this is very verbose.

Is there something simpler, like some clever if let?

like image 244
TPReal Avatar asked Jul 17 '26 02:07

TPReal


1 Answers

check it directly:

if Some(my_string) == q {
}

or (to keep my_string alive)

if Some(&my_string) == q.as_ref() {
}

There will be (probably) a contains() function in future rust versions which can be used like

if q.contains(&my_string) {
}

It is more flexible because it allows to compare different datatypes (when they implement PartialEq). See https://github.com/rust-lang/rust/issues/62358

like image 173
ensc Avatar answered Jul 19 '26 09:07

ensc