struct Cacher where T: Fn(u32) -> u32, { callculation: T, value: Option, } impl Cacher where T: Fn(u32) -> u32, { fn new(callculation: T) -> Cacher { Cacher { callculation, value: None, } } fn value(&mut self, arg: u32) -> u32 { match self.value { Some(v) => v, None => { let v = (self.callculation)(arg); self.value = Some(v); v } } } } #[cfg(test)] mod tests { use crate::Cacher; #[test] fn call_with_diffrernt_values() { let mut c = Cacher::new(|a| a); let v1 = c.value(1); // 此时闭包结果已经为1 let v2 = c.value(2); // 再输入2返回的闭包结果依旧为2 assert_eq!(v2, 2); // 测试不通过 } }