如何在枚举引用上匹配
?我正在使用返回对枚举的引用的依赖项,我需要读取枚举包含的值。在下面的示例中,我关心的是将 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`
最佳答案
这是行不通的。在第一个 ARM 上返回 &String
,在第二个 ARM 上返回 String
。
如果你克隆 x
它会工作,但不清楚你真正想要什么。
let final_val = match ref_option {
&Some(ref x) => x.clone(),
_ => String::from("not Set"),
};
编辑:
I would like it to be a string
然后提到的解决方案就是要走的路。然而,如果你真的不需要 String
,你应该使用 tafia's solution。 :
let final_val = match *ref_option {
Some(ref x) => x,
_ => "not Set",
};
关于rust - 匹配枚举引用并返回 "match arms have incompatible types"中的字符串结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49441484/