Skip to content
Justice Tech School

Option and Result

Option<T> is Some(value) or None, replacing null. Result<T, E> is Ok(value) or Err(error). The ? operator returns early on errors.

Example
fn find(v: &[i32], x: i32) -> Option<usize> {
    v.iter().position(|&n| n == x)
}
fn parse(s: &str) -> Result<i32, std::num::ParseIntError> {
    let n: i32 = s.parse()?;
    Ok(n * 2)
}
println!("{:?} {:?}", find(&[1, 2, 3], 2), find(&[1], 9));
println!("{:?}", parse("21"));
match parse("x") {
    Ok(n) => println!("{}", n),
    Err(_) => println!("not a number"),
}

Result

Some(1) None
Ok(42)
not a number

Exercise

Missing value variant.

Option has Some and 

Quiz Test

Does Rust have null?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.