Check if Option<String> is Some(my_string)

Viewed 2437

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?

4 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

I really like the answer provided by @ensc but it consumes my_string; here is a version that does not.

fn main() {
    let my_string = String::from("abcd");
    let q1: Option<String> = Some(String::from("abcd"));
    let q2: Option<String> = Some(String::from("abc"));
    let q3: Option<String> = None;
    // if Some(my_string) == q1 { // this will CONSUME my_string
    if Some(&my_string) == q1.as_ref() {
        println!("The same {:?}", q1);
    }
    // if Some(my_string) == q2 { // this will CONSUME my_string
    if Some(&my_string) == q2.as_ref() {
        println!("The same {:?}", q2);
    }
    // if Some(my_string) == q3 { // this will CONSUME my_string
    if Some(&my_string) == q3.as_ref() {
        println!("The same {:?}", q3);
    }
}

Just use if let:

fn main() {
    let s = Some("abc".to_string());
    if let Some("abc") = s.as_ref().map(|s: &String| s as &str) {
        println!("Ok")
    }
}

On the Rust book :

let some_u8_value = Some(0u8);
match some_u8_value {
    Some(3) => println!("three"),
    _ => (),
}

Is equivalent of :

if let Some(3) = some_u8_value {
    println!("three");
}
Related