gpt4 book ai didi

rust - 我如何借用选项中的项目或在没有时创建新项目?

转载 作者:行者123 更新时间:2023-11-29 08:09:58 26 4
gpt4 key购买 nike

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

基本上,创造的值(value)不会存在足够长的时间。获取对 Some 中的值的引用或创建一个值(如果它是 None)并使用该引用的最佳方法是什么?

最佳答案

你也可以只写:

None => "new thing created"

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

替代方案也可以是:

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

关于rust - 我如何借用选项中的项目或在没有时创建新项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51805406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com