如何在 None 时借用选项中的项目或创建新项目?

How can I borrow the item in an Option or create a new item when it's None?

当我有一个 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);
}

playground

错误:

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 并使用引用)的最佳方法是什么?

我发现的唯一方法是创建一个 "dummy variable" 来保存创建的项目并赋予它生命周期:

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);
}

playground

你也可以只写:

None => "new thing created"

通过此调整,您的代码初始变体无需额外的变量绑定即可编译。

替代方案也可以是:

let ref_to_thing = my_opt.unwrap_or("new thing created".to_string());

如果您不介意就地改变 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);
}