这个问题在这里已经有了答案:
Cannot move out of value which is behind a shared reference when unwrapping
(2 个回答)
How to get an Option's value or set it if it's empty?
(1 个回答)
11 个月前关闭。
我正在努力改进 Cacher
The Rust Programming Language 中描述的类型.建议的改进之一指出 Cacher
应该可以用于多种类型。为此,我编写了以下代码:
struct Cacher<T, U>
where
T: Fn(&U) -> U,
{
calculation: T,
value: Option<U>,
}
impl<T, U> Cacher<T, U>
where
T: Fn(&U) -> U,
{
fn new(calculation: T) -> Cacher<T, U> {
Cacher {
calculation,
value: None,
}
}
fn value(&mut self, arg: &U) -> &U {
match self.value {
Some(v) => &v,
None => {
let v = (self.calculation)(arg);
self.value = Some(v);
&v
}
}
}
}
编译器提示:error[E0507]: cannot move out of `self.value.0` which is behind a mutable reference
--> src/lib.rs:21:15
|
21 | match self.value {
| ^^^^^^^^^^ help: consider borrowing here: `&self.value`
22 | Some(v) => &v,
| -
| |
| data moved here
| move occurs because `v` has type `U`, which does not implement the `Copy` trait
error[E0515]: cannot return reference to local variable `v`
--> src/lib.rs:22:24
|
22 | Some(v) => &v,
| ^^ returns a reference to data owned by the current function
error[E0515]: cannot return reference to local variable `v`
--> src/lib.rs:26:17
|
26 | &v
| ^^ returns a reference to data owned by the current function
error[E0382]: borrow of moved value: `v`
--> src/lib.rs:26:17
|
24 | let v = (self.calculation)(arg);
| - move occurs because `v` has type `U`, which does not implement the `Copy` trait
25 | self.value = Some(v);
| - value moved here
26 | &v
| ^^ value borrowed here after move
我想这是因为 v
是函数的局部。但是,鉴于实际数据存在于结构中,该结构存在于 value
之外。方法,是否不可能以任何方式返回对此数据的引用?如果不是这样,那么我需要做什么才能获得 Cacher
的功能拥有计算数据并在需要时返回引用?
最佳答案
你几乎明白了。您只需要返回对对象的引用 内 Option
:
struct Cacher<T, U>
where
T: Fn(&U) -> U
{
calculation: T,
value: Option<U>,
}
impl<T, U> Cacher<T, U>
where
T: Fn(&U) -> U
{
fn new(calculation: T) -> Cacher<T, U> {
Cacher {
calculation,
value: None,
}
}
fn value(&mut self, arg: &U) -> &U {
if self.value.is_none() {
let v = (self.calculation)(arg);
self.value = Some(v);
}
self.value.as_ref().unwrap()
}
}
Playground
关于rust - 如何返回对 optional 结构字段内值的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63980290/