0
我剛開始學習Rust並通過Rust書進行工作。其中一章通過幾個例子,並以「嘗試進行這種通用」類型的建議練習結束。我一直對此感到震驚。你開始的半通用型是這樣的:「值」返回引用具有通用Fn特徵/值的泛型類型
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值getter中。我不確定我是否關閉或者我只是完全錯誤的路徑。那麼我要去哪裏?
啊,做到了!在教程的某處,我錯過了解包是一個*移動*。謝謝! – Chris