abh*_*ink 5 reference rust option-type
我正在尝试改进Rust 编程语言Cacher中描述的类型。建议的改进之一指出应该可用于多种类型。为此,我编写了以下代码: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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨:
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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想这是因为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()
}
}
Run Code Online (Sandbox Code Playgroud)