当我有一个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
基本上,创造的价值活得不够长。获取对 a 中的值的引用Some
或创建一个值(如果它是 aNone
并使用该引用)的最佳方法是什么?