Just another programming blog

Factual accuracy is not guaranteed

Rust: The heck is an option<> supposed to mean?


Option is similar to the null of other languages, except it is type safe.
You must transform an Option before you can use it.
You may see it like this Option<usize> or like this Option<Vec<u32>> or maybe like this std::Option<()>, or some other way – the possibilities are endless. Here’s some examples of how you can use an option…

Examples

Create an option and consume it
fn main() {
     // create an option with a value
    let number_option = Option::Some(32);

    // crash with an error message if the option is empty
    let number = number_option.unwrap(); 

    println!("{}", number);
}
Create an empty option and consume it
fn main() {
    // create it manually without a value
    let number_option: Option<u32> = Option::None;  

    // crash with an error message if the option is empty
    let number = number_option.unwrap();

    println!("{}", number);
}
Get an option from a function and consume it
fn main() {
    // create 2 numbers with 8 bits in size 
    let number1: u8 = 50;
    let number2: u8 = 10;

    // use a function that can fail (this one fails if the result can't fit into 8 bits)
    let number3_option = number1.checked_mul(number2);

    // choose to crash if the function failed
    let number3 = number3_option.unwrap();

    println!("{}", number3);
}
Get an option from a function and print it
// get an option from a function and print it
fn main() {
    let letters = "😍";

    // will faill if t is not in letters  
    let position = letters.find("t");

    // debug print the option, without crashing
    println!("position is '{:?}'", position); 
}
Get an option from a function and consume it better
fn main() {
    let my_string = "Öl".to_string();

    // Can fail if the 0th and 1st byte are do not make up a complete character.
    let slice_option = my_string.get(0..1);

    // give a nice error message if it fails
    let slice = slice_option.expect("Failed to get first bytes");

    println!("the first character is '{}'", slice);
}
Do something different if it’s empty
fn main() {
    let list = vec!['m', 'e', 'o', 'w'];

    let tenth_option = list.get(10);

    match tenth_option {
        None => {println!("There was no tenth :(");}
        Some(tenth) => {println!("The tenth character is {:?}", tenth)}
    }
}

Further reading


One response to “Rust: The heck is an option<> supposed to mean?”

Leave a Reply

Your email address will not be published. Required fields are marked *