Search code examples
rustoption-type

Best way to check if Option contains a specific Some value?


You can't do something such as:

if option.is_some() && option == 1 {
    // ...
}

Since if option.is_some() == false the 2nd comparison would error.

What is the best way to do something such as this?

What I'm doing right now:

if option.is_some() {
    if option == 1 {
        // ...
    }
}

Solution

  • Pattern matching is a powerful tool, use it! Instead of a regular if, use an if let:

    if let Some(1) = option {
        // --snip--
    }
    

    For more information about pattern matching, please consult The Rust Reference.