gpt4 book ai didi

rust - 在惰性静态 RwLock> 中返回对 T 的引用?

转载 作者:行者123 更新时间:2023-12-03 11:26:31 25 4
gpt4 key购买 nike

我有一个惰性静态结构,我希望能够在程序执行开始时将其设置为某个随机值,然后再获取。这个愚蠢的小片段可以用作示例:

use lazy_static::lazy_static;
use std::sync::RwLock;

struct Answer(i8);

lazy_static! {
static ref ANSWER: RwLock<Option<Answer>> = RwLock::new(None);
}

fn answer_question() {
*ANSWER.write().unwrap() = Some(Answer(42));
}

fn what_is_the_answer() -> &'static Answer {
ANSWER
.read()
.unwrap()
.as_ref()
.unwrap()
}
此代码无法编译:
error[E0515]: cannot return value referencing temporary value
--> src/lib.rs:15:5
|
15 | ANSWER
| _____^
| |_____|
| ||
16 | || .read()
17 | || .unwrap()
| ||_________________- temporary value created here
18 | | .as_ref()
19 | | .unwrap()
| |__________________^ returns a value referencing data owned by the current function
我知道您不能返回对临时值的引用。但我想返回对 ANSWER 的引用这是静态的 - 与临时相反!我猜是 RwLockReadGuard第一次调用 unwrap退货是什么问题?
我可以通过更改返回类型来编译代码:
fn what_is_the_answer() -> RwLockReadGuard<'static, Option<Answer>> {
ANSWER
.read()
.unwrap()
}
但是现在调用代码变得非常不符合人体工程学 - 我必须进行两次额外调用才能获得实际值:
what_is_the_answer().as_ref().unwrap()
我可以以某种方式返回对静态 ANSWER 的引用吗?从这个功能?我可以让它返回一个 RwLockReadGuard<&Answer>也许通过某种方式映射?

最佳答案

once_cell 为此设计:使用 .set(...).unwrap()answer_question.get().unwrap()what_is_the_answer .

关于rust - 在惰性静态 RwLock<Option<T>> 中返回对 T 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63318867/

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