How can I pattern match against an Option?

后端 未结 4 1008
臣服心动
臣服心动 2021-01-01 10:13

I can straight-forwardly match a String in Rust:

let a = \"hello\".to_string();

match &a[..] {
    \"hello\" => {
        println!(\"Mat         


        
4条回答
  •  迷失自我
    2021-01-01 10:53

    In some cases, you can use unwrap_or to replace Option::None with a predefined &str you don't want to handle in any special way.

    I used this to handle user inputs:

    let args: Vec = env::args().collect();
    
    match args.get(1).unwrap_or(&format!("_")).as_str() {
        "new" => {
            print!("new");
        }
        _ => {
            print!("unknown string");
        }
    };
    

    Or to match your code:

    let option = Some("hello");
    
    match option.unwrap_or(&format!("unhandled string").as_str()) {
        "hello" => {
            println!("hello");
        }
        _ => {
            println!("unknown string");
        }
    };
    

提交回复
热议问题