我如何在枚举参考上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);
}
答案 0 :(得分:4)
这不起作用。在第一个手臂上,您返回&String
,在第二个手臂中返回String
。
如果您克隆x
,它会有效,但目前还不清楚您真正想要的是什么。
let final_val = match ref_option {
&Some(ref x) => x.clone(),
_ => String::from("not Set"),
};
编辑:
我希望它是一个字符串
然后提到的解决方案就是要走的路。但是,如果您真的不需要String
,则应使用tafia's solution:
let final_val = match *ref_option {
Some(ref x) => x,
_ => "not Set",
};
答案 1 :(得分:2)
有两个问题
您必须在*ref_option
上匹配,或在分支中拥有&Some(...)
和&None
。匹配*ref_option
更加惯用。
匹配后,您使用的ref x
是String
的引用(相当于&String
)。因此,您clone
,as suggested by Tim或在两个分支中都返回&String
(取消引用&str
)。
总而言之,您可以:
let final_val = match *ref_option {
Some(ref x) => x,
_ => "not Set",
};