For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/rust-code-quality/panicking-unwrap.md. A documentation index is available at /llms.txt.

Call to unwrap or expect on a known None or Err value

This product is not supported for your selected Datadog site. ().

Metadata

ID: rust-code-quality/panicking-unwrap

Language: Rust

Severity: Error

Category: Error Prone

Description

Calling .unwrap() or .expect() on an Option or Result value that is provably None or Err at that point will always panic at runtime. This is not caught at compile time and will crash the program when that code path runs.

Two patterns are detected: a variable initialized to None or Err(...) and immediately unwrapped on the next line, and an .unwrap() or .expect() call directly inside a branch already guarded by .is_none() or .is_err().

Non-Compliant Code Examples

fn get_user_age(age: Option<u32>) -> u32 {
    if age.is_none() {
        return age.unwrap();
    }
    0
}

fn parse_port(input: &str) -> u16 {
    let result = input.parse::<u16>();
    if result.is_err() {
        return result.unwrap();
    }
    8080
}

fn bad_let_err_unwrap() -> i32 {
    let z: Result<i32, &str> = Err("failed");
    return z.unwrap();
}

Compliant Code Examples

fn safe_is_some_guard(x: Option<u32>) -> u32 {
    if x.is_some() {
        return x.unwrap();
    }
    0
}

fn safe_different_var(a: Option<u32>, b: Option<u32>) -> u32 {
    if a.is_none() {
        return b.unwrap();
    }
    0
}

fn safe_let_some_adjacent() -> i32 {
    let x: Option<i32> = Some(5);
    x.unwrap()
}

fn safe_let_none_reassigned() -> i32 {
    let mut x: Option<i32> = None;
    x = Some(42);
    x.unwrap()
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security