Why is this an issue?

Using unwrap() in conditions where it will always fail leads to unexpected panics and unclear error handling. It’s likely a mistake and checking that there is indeed a wrapped value and not a none one was intended instead, which would require inverting the condition. However, if panicking was indeed intended, then one should use panic! explicitly to make the intention clear and readable.

Code examples

Noncompliant code example

let option = Some(0);
fn do_something_with(_x: usize) {}
if option.is_none() {
    do_something_with(option.unwrap()); // Noncompliant: This code will always panic.
}

Compliant solution

let option = Some(0);
fn do_something_with(_x: usize) {}
if option.is_some() {
    do_something_with(option.unwrap()); // Compliant: Inverted condition to ensure unwrap is safe.
}

// or

if option.is_none() {
    panic!("Option was none when it was expected to be some."); // Compliant: Explicit panic with a message.
}

Resources

Documentation