unwrap() inside a branch already guarded by is_some()/is_ok()

ID

rust.maintainability.unnecessary_unwrap

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Idiom

Language

Rust

Description

Reports a call to unwrap() on a value inside the if branch that has just tested the same value with is_some() or is_ok().

Rationale

The test and the unwrap inspect the value twice and keep the guarantee only in the programmer’s head: nothing ties them together, so moving the unwrap out of the branch, or adding a condition to the if, turns working code into a panic with no compiler complaint. The pattern also leaves the inner value borrowed rather than bound, which forces extra clones or as_ref() calls further down.

The following code illustrates the pattern detected by this rule:

fn label(name: Option<String>) -> String {
    if name.is_some() {
        // FLAGGED: unwrap() inside a branch already guarded by is_some()/is_ok()
        name.unwrap()
    } else {
        "anonymous".to_string()
    }
}

Remediation

Replace the pair with if let Some(value) = opt (or if let Ok(value) = res), which tests and binds in one step and lets the compiler enforce the relationship. For a value-producing expression, map_or_else, unwrap_or_else or match express the same thing without the second inspection.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved