use std::{thread, time::Duration}; fn main() { fn generate_workout(intensity: u32, random_number: u32) { // 定义一个闭包 let expensive_closure = |num| { println!("calculating slowyy ..."); thread::sleep(Duration::from_secs(2)); num }; if intensity < 25 { println!("Today, do {} pushups!", expensive_closure(intensity)); println!("Next, do {} situps!", expensive_closure(intensity)); } else { if random_number == 3 { println!("Take a break today! Remember to stay hydrated!"); } else { println!("Today, run for {} minutes!", expensive_closure(intensity)); } } } // 另一种解决方案 // 创建一个struct,它持有闭包及其调用结果 // - 只会在需要结果时才执行该闭包 // - 可缓存结果 // 这个模式通常叫做记忆化(memoization)或延时计算(lazy evaluation) 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 } } } } fn generate_workout2(intensity: u32, random_number: u32) { // 定义一个闭包 let mut expensive_closure = Cacher::new(|num| { println!("calculating slowyy ..."); thread::sleep(Duration::from_secs(2)); num }); if intensity < 25 { println!("Today, do {} pushups!", expensive_closure.value(intensity)); println!("Next, do {} situps!", expensive_closure.value(intensity)); } else { if random_number == 3 { println!("Take a break today! Remember to stay hydrated!"); } else { println!( "Today, run for {} minutes!", expensive_closure.value(intensity) ); } } } let sumulated_user_specified_value = 10; let simulated_randon_number = 7; generate_workout2(sumulated_user_specified_value, simulated_randon_number); let x = 4; let equual_to_x = |z| x == x + z; let y = 4; println!("{}", x); assert!(equual_to_x(y)); let x = vec![1,2,3,4]; let equal_to_x = move |z| z == x; println!("can't use x here: {:?}", x); // 报错:x已失效 let y =vec![1,2,3]; assert!(equal_to_x(y)); }