頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/
例子://實現一個快取,值處理第一次傳入的值並儲存
struct Cacher<T>
where T: Fn(u32) -> u32 //泛型和fn trait
{
calculation: T, //T是一個閉包
value: Option<u32>,
}
impl<T> Cacher<T>
where T: Fn(u32) -> u32
{
fn new (calculation: T) -> Cacher<T> {
Cacher {
calculation,
value: None,
}
}
fn value(&mut self, arg: u32) -> u32 {
match self.value {
Some(v) => v,
None => {
let v = (self.calculation)(arg);
self.value = Some(v);
v
},
}
}
}
fn main() {
let mut c = Cacher::new(|a| a);
let v1 = c.value(1);
println!("v1 = {}", v1);
let v2 = c.value(2);
println!("v2 = {}", v2);
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結