Rust 1.99 (2024 edition) reference · Option and Result

Rust The ? operator Operator

Propagate errors from functions returning Result or Option: unwrap Ok values and return early on Err.

Rust 1.99 (2024 edition)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

expr?   (in a function returning Result<_, E> where the error converts with From)

Parameters

ParameterDescription
Result Err(e) returns Err(From::from(e)) from the function.
Option None returns None from the function.
main() -> Result<(), Box<dyn Error>> Use ? in main.

Examples

Example 1
fn sum_csv(line: &str) -> Result<i64, std::num::ParseIntError> {
    let mut total = 0;
    for part in line.split(',') {
        total += part.trim().parse::<i64>()?;
    }
    Ok(total)
}

fn main() {
    println!("{:?}", sum_csv("1,2,3"));
    println!("{:?}", sum_csv("1,x,3").map_err(|e| e.to_string()));
}

Output

Ok(6)
Err("invalid digit found in string")

Run this on your computer — see “Get Started” for setup.

? with Option
fn first_digit(s: &str) -> Option<u32> {
    let c = s.chars().find(|c| c.is_ascii_digit())?;
    c.to_digit(10)
}

fn main() {
    println!("{:?}", first_digit("abc7d"));
    println!("{:?}", first_digit("none"));
}

Output

Some(7)
None

Run this on your computer — see “Get Started” for setup.

Was this page helpful?