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?
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
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