How do you pass a Rust function as a parameter?

前端 未结 2 1910
半阙折子戏
半阙折子戏 2020-11-30 23:25

Can I pass a function as a parameter? If not, what is a good alternative?

I tried some different syntaxes but I have not found the right one. I know I can do this:

2条回答
  •  长情又很酷
    2020-12-01 00:04

    Fn, FnMut and FnOnce, outlined in the other answer, are closure types. The types of functions that close over their scope.

    Apart from passing closures Rust also supports passing simple (non-closure) functions, like this:

    fn times2(value: i32) -> i32 {
        2 * value
    }
    
    fn fun_test(value: i32, f: fn(i32) -> i32) -> i32 {
        println!("{}", f (value));
        value
    }
    
    fn main() {
        fun_test (2, times2);
    }
    

    fn(i32) -> i32 here is a function pointer type.

    If you don't need a full-fledged closure than working with function types is often simpler as it doesn't have to deal with those closure lifetime nicities.

提交回复
热议问题