匹配枚举引用并返回一个字符串导致"匹配武器具有不兼容的类型"

时间:2018-03-23 02:30:23

标签: rust

我如何在枚举参考上x := uint(42) y := 42 // defaults to type int if x == y { println("this won't complile!") } ?我正在使用一个依赖项,它返回对枚举的引用,我需要读取枚举所包含的值。在以下示例中,我关心的是使用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);
}

2 个答案:

答案 0 :(得分:4)

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

如果您克隆x,它会有效,但目前还不清楚您真正想要的是什么。

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

Playground

编辑:

  

我希望它是一个字符串

然后提到的解决方案就是要走的路。但是,如果您真的不需要String,则应使用tafia's solution

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

Playground

答案 1 :(得分:2)

有两个问题

  1. 您必须在*ref_option上匹配,或在分支中拥有&Some(...)&None。匹配*ref_option更加惯用。

  2. 匹配后,您使用的ref xString的引用(相当于&String)。因此,您cloneas suggested by Tim或在两个分支中都返回&String(取消引用&str)。

  3. 总而言之,您可以:

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