代码之家  ›  专栏  ›  技术社区  ›  ZNackasha

匹配枚举引用并返回字符串会导致“match arms have compatible types”(匹配臂具有不兼容的类型)

  •  -1
  • ZNackasha  · 技术社区  · 7 年前

    我该怎么做 match 在枚举引用上?我使用的依赖项返回对枚举的引用,我需要读取枚举包含的值。在下面的示例中,我关心的是分配 final_val 具有 x :

    fn main() {
        let test_string = String::from("test");
        let option: std::option::Option<String> = Some(test_string);
        let ref_option = &option;
    
        let final_val = match ref_option {
            Some(x) => x,
            _ => String::from("not Set"),
        };
    
        println!("{:?}", final_val);
    }
    

    如果我按照编译器的建议添加 & 到类型 Some ref x :

    fn main() {
        let test_string = String::from("test");
        let option: std::option::Option<String> = Some(test_string);
        let ref_option = &option;
    
        let final_val = match ref_option {
            &Some(ref x) => x,
            _ => String::from("not Set"),
        };
    
        println!("{:?}", final_val);
    }
    

    我遇到以下错误,我不知道如何解决:

    error[E0308]: match arms have incompatible types
      --> src\main.rs:6:21
       |
    6  |       let final_val = match ref_option
       |  _____________________^
    7  | |     {
    8  | |         &Some(ref x) => x,
    9  | |         _ => String::from("not Set" ),
       | |              ------------------------ match arm with an incompatible type
    
    10 | |     };
       | |_____^ expected reference, found struct `std::string::String`
       |
       = note: expected type `&std::string::String`
                  found type `std::string::String`
    
    2 回复  |  直到 7 年前
        1
  •  6
  •   Tim Diekmann suresh madaparthi    7 年前

    这不起作用。在第一只手臂上返回 &String ,在第二只手臂上 String

    如果你克隆的话就可以了 x ,但不清楚你真正想要什么。

    let final_val = match ref_option {
        &Some(ref x) => x.clone(),
        _ => String::from("not Set"),
    };
    

    Playground

    编辑:

    我想要一根绳子

    那么,前面提到的解决方案就是要走的路。然而,如果你真的不需要 一串 ,你应该和 tafia's solution :

    let final_val = match *ref_option {
        Some(ref x) => x,
        _ => "not Set",
    };
    

    Playground

        2
  •  2
  •   Shepmaster Tim Diekmann    7 年前

    有两个问题

    1. 您必须匹配 *ref_option 或者有 &Some(...) &None 在树枝上。正在匹配 *ref\U选项 更为惯用。

    2. 匹配后,使用 ref x 这是对 String (相当于 &String )。所以要么你 clone as suggested by Tim 或者您返回 &一串 (取消对a的引用 &str )在两个分支中。

    总之,您可以:

    let final_val = match *ref_option {
        Some(ref x) => x,
        _ => "not Set",
    };