一、闭包入门
use std::thread;
use std::time::Duration;
fn main(){
let specified_value = 10;
let random_number = 7;
generate_workout(specified_value,random_number);
}
fn generate_workout(intensity:u32,random_number:u32) {
// 定义一个函数闭包
let expensive_closure = |num| {
println!("calculate slowly");
thread::sleep(Duration::from_secs(2));
num;
};
// 然后传入函数闭包
if intensity < 25 {
println!("Today,do {} pushups!",expensive_calculate(intensity));
println!("Next do {} situps!", expensive_calculate(intensity));
} else {
if random_number == 3 {
println!("Take break today");
} else {
println!("Today,fun for {} minutes",expensive_calculate(intensity));
}
}
}
二、闭包的类型推断和标注
已经推断成String类型,就不能再推断成u32类型了
三、使用泛型参数和Fn Trait来存储闭包
use std::thread;
use std::time::Duration;
// 结构体存储闭包
struct Cacher<T>
where T: Fn(u32) -> u32,
{
calculation : 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 specified_value = 10;
let random_number = 7;
generate_workout(specified_value,random_number);
}
fn generate_workout(intensity:u32,random_number:u32) {
// 定义一个函数闭包
let mut expensive_closure = Cacher::new(|num| {
println!("calculate slowly");
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 break today");
} else {
println!("Today,fun for {} minutes",expensive_closure.value(intensity));
}
}
}