---
title: Call to unwrap or expect on a known None or Err value
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Call to unwrap or expect on a known None or Err value
---

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

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com, us2.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ({% placeholder "user-datadog-site-name" /%}).
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `rust-code-quality/panicking-unwrap`

**Language:** Rust

**Severity:** Error

**Category:** Error Prone

## Description{% #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{% #non-compliant-code-examples %}

```rust
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{% #compliant-code-examples %}

```rust
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()
}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 