如何在选项中借用该项目或在无选项时创建新项目?

sbd*_*o85 1 optional rust 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);
}
Run Code Online (Sandbox Code Playgroud)

操场

错误:

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
Run Code Online (Sandbox Code Playgroud)

基本上,创造的价值不够长.Some如果a是a None并使用引用,那么在a中引用值或创建值的最佳方法是什么?

lje*_*drz 5

你也可以写:

None => "new thing created"
Run Code Online (Sandbox Code Playgroud)

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

另一种选择也可以是:

let ref_to_thing = my_opt.unwrap_or("new thing created".to_string());
Run Code Online (Sandbox Code Playgroud)