Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Demo None handling with Option

This is another example to demonstrate an Option that can be either None or Some(value).

fn main() {
    let name = get_name(true);
    say_hi(name);

    let name = get_name(false);
    say_hi(name);
}

fn get_name(good: bool) -> Option<String> {
    if good {
        Some(String::from("Gabor"))
    } else {
        None
    }
}

fn say_hi(name: Option<String>) {
    match name {
        Some(text) => println!("Hello {text}"),
        None => println!("Welcome! My name is Rust."),
    }
}

See original idea on What is Rust and why is it so popular?


  • Option
  • match
  • Some
  • None