码迷,mamicode.com
首页 > 其他好文 > 详细

Rust中的闭包

时间:2019-08-31 12:36:03      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:gen   hydra   elf   break   src   int   ati   完全   alc   

这个功能有点高级,

暂时理解不完全,

先把代码练正确吧。

use std::thread;
use std::time::Duration;

struct Cacher<T> where T: Fn(u32) -> u32 {
    caculation: T,
    value: Option<u32>,
}

impl<T> Cacher<T> where T: Fn(u32) -> u32 {
    fn new(caculation: T) -> Cacher<T> {
        Cacher {
            caculation, 
            value: None,
        }
    }

    fn value(&mut self, arg: u32) -> u32 {
        match self.value {
            Some(v) => v,
            None => {
                let v = (self.caculation)(arg);
                self.value = Some(v);
                v
            },
        }
    }
}

fn main() {
    let simulated_user_specified_value = 6;
    let simulated_random_number = 30;

    generate_workout(
        simulated_user_specified_value,
        simulated_random_number
    );
}

fn generate_workout(intensity: u32, random_number: u32) {
    let mut expensive_result = Cacher::new(|num| {
        println!("calculating slowly...");
        thread::sleep(Duration::from_secs(2));
        num
    });

    if intensity < 25 {
        println!("Today, do {} pushups",
        expensive_result.value(intensity));
        println!("Next, do {} situps!",
        expensive_result.value(intensity));
    } else {
        if random_number == 3 {
            println!("Take a break today! Remember to stay hydrated!");
        } else {
            println!("Today, run for {} minutes!",
            expensive_result.value(intensity));
        }
    }
}

/*
fn simulated_expensive_calculation(num: u32) -> u32 {
    println!("calculating slowly...");
    thread::sleep(Duration::from_secs(2));
    num

 }
 */

技术图片

Rust中的闭包

标签:gen   hydra   elf   break   src   int   ati   完全   alc   

原文地址:https://www.cnblogs.com/aguncn/p/11438380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!