struct Cache where T: Fn(u32) -> u32, { calc: T, value: Option, } impl Cache where T: Fn(u32) -> u32, { fn new(calc: T) -> Cache { Cache { calc, value: None } } fn value(&mut self, v: u32) -> u32 { match self.value { Some(v) => v, None => { // 必须加括号 let v = (self.calc)(v); self.value = Some(v); v } } } } fn main() { let mut c = Cache::new(|x| x + 1); let v1 = c.value(1); println!("{}", v1); let v2 = c.value(2); println!("{}", v2); }