【发布时间】:2018-02-11 10:41:06
【问题描述】:
我刚刚开始学习 Rust 并阅读 Rust 书。其中一章通过几个示例引导,并以“尝试使这种通用”类型的建议练习结束。我一直在全力以赴。您开始使用的半泛型类型是这样的:
struct Cacher<T>
where T: Fn(i32) -> i32
{
value: Option<i32>,
// leaving out rest for brevity
然后我开始转换它,以便 Fn 特征也是通用的,这也直接影响“价值”。所以这就是我想出的:
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: Option::None,
}
}
fn value(&mut self, arg: U) -> &U {
match self.value {
Some(ref v) => v,
None => {
let v = (self.calculation)(arg);
self.value = Some(v);
// problem is returning reference to value that was in
// v which is now moved, and unwrap doesn't seem to work...
},
}
}
}
我所有的问题都在 fn 值获取器中。我不确定我是 close 还是我只是走错了路。那么我在哪里出轨呢?
【问题讨论】:
标签: rust closures lifetime borrow-checker ownership-semantics