How can I pattern match against an Option?

后端 未结 4 1005
臣服心动
臣服心动 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:59

    It's a known limitation of Rust's patterns.

    Method calls (including internal methods for operators like ==) automatically call .deref() as needed, so String gets automagically turned into &str for comparisons with literals.

    On the other hand, the patterns are quite literal in their comparisons, and find that String and &str are different.

    There are two solutions:

    1. Change Option to Option<&str> before matching on it: Some(a).as_ref().map(String::as_str). The as_ref() makes Option<&String> (preventing move), and as_str() then unambiguously references it as a &str.

    2. Use match guard: match Some(a) { Some(ref s) if s == "hello" => … }. Some(ref s) matches any String, and captures it as s: &String, which you can then compare in the if guard which does the usual flexible coercions to make it work.

    See also:

    • Converting from Option to Option<&str>

提交回复
热议问题