rust用BTreeMap保存closure

use std::collections::BTreeMap;

struct Foo{
    entry:BTreeMap<i32,Box<Fn(i32)->i32>>,
}

impl Foo{
    fn new()->Foo{
        Foo{
            entry:BTreeMap::new(),
        }
    }

    fn add<F:Fn(i32)->i32 +'static>(&mut self,i:i32,f:F){
        self.entry.insert(i,Box::new(f));
    }

    fn print_add(&self,i:i32){
        if let Some(x) = self.entry.get(&i){
            println!("{}",x(20));
        }   
    }


fn main(){
    let mut f = Foo::new();
    {
        f.add(100,|i|i+100);
        f.add(200,|i|i+300);
    }

    f.print_add(100);
}

Play地址:http://is.gd/DOO2lR

输出:

120

你可能感兴趣的:(closure,Rust,btreemap)