在rust里使用c样式的函数指针

Fn(i32)->i32这个是trait,&Fn(i32)->i32这个是trait object,有lifetime的
fn(i32)->i32这种就是c里的函数指针了,这个是没有lifetime的

fn hello(i:i32)->i32{
    println!("hello:{}",i);
    i+100
}

fn hi(f:fn(i32)->i32){
    f(3);
}

struct Foo{
    f:fn(i32)->i32,
}

impl Foo{
    fn say(&self,i:i32){
        (self.f)(i);
    }

    fn greeting(i:i32)->i32{
        println!("how are you:{}",i);
        i+200
    }
}

fn main(){
    let ff = Foo{f:hello};
    ff.say(123);

    let f2 = Foo{f:Foo::greeting};
    f2.say(321);
}

Play地址:http://is.gd/0fL0a5

输出结果:

hello:123
how are you:321

你可能感兴趣的:(callback,回调函数,Rust,c样式函数指针)