use std::time::Duration;
use std::thread;
fn main() {
let value = 10;
let number = 7;
generate_workout(value, number);
}
struct Cache<T>
where T: Fn(u32) -> u32 {
calculation: T,
value: Option<u32>,
}
impl<T> Cache<T>
where T: Fn(u32) -> u32
{
fn new(calculation: T) -> Cache<T> {
Self { 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 generate_workout(num: u32, random_number: u32) {
let mut expensive_result = Cache::new(|n| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
n
});
if num < 25 {
println!("Today,do {} pushups!", expensive_result.value(num));
println!("Next,do {} situps!", expensive_result.value(num))
} else {
println!("Today,run for {} minutes!", expensive_result.value(num));
}
}
定义结构体,结构体有个泛型参数T,然后有个约束,T就代表这个闭包的类型,而闭包的类型,它的约束是这样的,Fn接收一个u32类型,返回值也是u32类型