ruk·si

🦀 Rust
Option

Updated at 2024-01-04 06:26

Option signifies a value that might exist or not. You usually either .is_some() + .unwrap() the option, match it or if let Some(value) = option {}.

// enum Option<T> {
//     None,
//     Some(T),
// }

fn main() {
    let o1: Option<i32> = Some(128);
    assert_eq!(o1.unwrap(), 128);

    let o2: Option<i32> = None;
    match o2 {
        Some(number) => println!("{}", number),
        None => println!("There is no number!")
    }
}
fn take_fifth(value: Vec<i32>) -> Option<i32> {
    if value.len() < 5 {
        None
    } else {
        Some(value[4])
    }
}

fn main() {
    let new_vec = vec![1, 2];
    let bigger_vec = vec![1, 2, 3, 4, 5];
    assert_eq!(take_fifth(new_vec), None);
    assert_eq!(take_fifth(bigger_vec), Some(5));
}

You can also just take a reference out of an Option. Here we call the as_ref method on the Option because we want a reference to the value inside the Option rather than take the ownership of the value.

my_option.as_ref().unwrap()

Sources