gpt4 book ai didi

rust - 如何修复 'creates a temporary which is freed while still in use'?

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

我正在学习Rust并尝试实现类似于缓存的结构来缓存对象,但是我陷入了错误。
src/main.rs

// The Result object to be cached
struct Result {
value: u32,
}

struct Cacher<'a, T>
where
T: Fn(u32) -> u32,
{
calc: T,
value: Option<&'a Result>,
}

impl<'a, T> Cacher<'a, T>
where
T: Fn(u32) -> u32,
{
fn new(calc: T) -> Cacher<'a, T> {
Cacher { calc, value: None }
}

fn get_value(&mut self, arg: u32) -> &Result {
match self.value {
Some(v) => v,
None => {
let v = (self.calc)(arg);
self.value = Some(&Result { value: v });
self.value.unwrap()
}
}
}
}
这将导致以下错误:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:28:40
|
15 | impl<'a, T> Cacher<'a, T>
| -- lifetime `'a` defined here
...
28 | self.value = Some(&Result { value: v });
| -------------------^^^^^^^^^^^^^^^^^^^-- temporary value is freed at the end of this statement
| | |
| | creates a temporary which is freed while still in use
| assignment requires that borrow lasts for `'a`
如何解决这个问题?

最佳答案

如果没有人拥有该值,则不能返回对该值的引用。
同样,在使用Cacher时,您需要确保get_value获得的引用不会超过Cacher本身。

// The Result object to be cached
struct Result {
value: u32,
}

struct Cacher<T>
where
T: Fn(u32) -> u32,
{
calc: T,
value: Option<Result>, // We need to own the Result
}

impl<T> Cacher<T>
where
T: Fn(u32) -> u32,
{
fn new(calc: T) -> Cacher<T> {
Cacher { calc, value: None }
}

fn get_value(&mut self, arg: u32) -> &Result {
match self.value {
Some(ref v) => v, // destructuring value by reference to it
None => {
let v = (self.calc)(arg);
self.value = Some(Result { value: v });
self.value.as_ref().unwrap() // unwrapping value by reference to it
}
}
}
}

关于rust - 如何修复 'creates a temporary which is freed while still in use'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63591292/

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