当我有一个Option
并想要引用其中的内容时,或者如果它是None
时创建内容,则会出现错误。
示例代码:
fn main() {
let my_opt: Option<String> = None;
let ref_to_thing = match my_opt {
Some(ref t) => t,
None => &"new thing created".to_owned(),
};
println!("{:?}", ref_to_thing);
}
错误:
error[E0597]: borrowed value does not live long enough
--> src/main.rs:6:18
|
6 | None => &"new thing created".to_owned(),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
| | |
| | temporary value dropped here while still borrowed
| temporary value does not live long enough
...
10 | }
| - temporary value needs to live until here
基本上,创建的值的寿命不足。在Some
中获取对None
中的值的引用或创建值并使用引用的最佳方法是什么?
答案 0 :(得分:5)
您也可以只写:
None => "new thing created"
通过此调整,您的代码初始变体将无需额外的变量绑定即可编译。
替代方法也可以是:
let ref_to_thing = my_opt.unwrap_or("new thing created".to_string());
答案 1 :(得分:4)
我发现的唯一方法是创建一个“虚拟变量”来保存所创建的项目并赋予其生命期:
fn main() {
let my_opt: Option<String> = None;
let value_holder;
let ref_to_thing = match my_opt {
Some(ref t) => t,
None => {
value_holder = "new thing created".to_owned();
&value_holder
}
};
println!("{:?}", ref_to_thing);
}
答案 2 :(得分:3)
如果您不介意将Option
突变,可以使用Option::method.get_or_insert_with
:
fn main() {
let mut my_opt: Option<String> = None;
let ref_to_thing = my_opt.get_or_insert_with(|| "new thing created".to_owned());
println!("{:?}", ref_to_thing);
}