使用泛型 Fn trait/value 返回对泛型类型的引用

Returning reference to generic type with generic Fn trait/value

我刚刚开始学习 Rust 并正在阅读 Rust 书籍。其中一章介绍了一些示例,并以 "try to make this generic" 类型的建议练习结束。我一直在努力解决这个问题。您开始使用的半通用类型是这样的:

struct Cacher<T>
    where T: Fn(i32) -> i32
{
    value: Option<i32>,
    // leaving out rest for brevity

然后我开始着手转换它,以便 Fn 特征也是通用的,这也直接影响 "value." 所以这就是我想出的:

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 值 getter 中。我不确定我是 close 还是完全走错了路。那么我要去哪里 rails?

and unwrap doesn't seem to work...

问题是 unwrap 按值接受它的参数,所以它被移动了。

self.value.as_ref().unwrap() 这样的东西应该可以解决问题。