Why does passing a closure to function which accepts a function pointer not work?

后端 未结 2 1288
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 16:50

In the second edition of The Rust Programming Language (emphasis mine):

Function pointers implement all three of the closure traits (Fn,

2条回答
  •  爱一瞬间的悲伤
    2020-12-03 17:33

    A closure isn't a function.

    You can pass a function to a function expecting a closure, but there's no reason for the reverse to be true.

    If you want to be able to pass both closures and functions as argument, just prepare it for closures.

    For example:

    let a = String::from("abc");
    
    let x = || println!("x {}", a);
    
    fn y() {
        println!("y")
    }
    
    fn wrap(c: impl Fn()) {
        c()
    }
    
    wrap(x); // pass a closure
    wrap(y); // pass a function
    

提交回复
热议问题