如何在“无”选项中借用该项目或创建一个新项目?

时间:2018-08-12 03:18:30

标签: rust optional borrow-checker borrowing

当我有一个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中的值的引用或创建值并使用引用的最佳方法是什么?

3 个答案:

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

playground

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