在rust中有2种方法来传入函数指针,一种通过 fn 另外一种是通过Fn FnMut FnOnce三兄弟

    1. fn call_fn_pointer(f: fn(&str) -> String) {
    2. let res = f("fn pointer");
    3. println!("{}", res);
    4. }
    5. fn main() {
    6. call_fn_pointer(|s| { s.to_string() });
    7. }

    或者

    1. fn call_fn_trait<T: Fn(&str) -> String>(f: T) {
    2. let res = f("fn trait");
    3. println!("{}", res);
    4. }
    5. fn main() {
    6. call_fn_trait(|s| { s.to_string() });
    7. }

    这两种方式都可以当做函数指针,区别是什么呢?

    Function pointers are pointers that point to code, not data. They can be called just like functions. Like references, function pointers are, among other things, assumed to not be null, so if you want to pass a function pointer over FFI and be able to accommodate null pointers, make your type Option with your required signature Plain function pointers are obtained by casting either plain functions, or closures that don’t capture an environment:


    1. let outer = String::from("hello");
    2. call_fn_pointer(|s| {
    3. println!("{}", outer.len());
    4. s.to_string()
    5. });
    6. call_fn_trait(|s| {
    7. println!("{}", outer.len());
    8. s.to_string()
    9. });
    10. error[E0308]: mismatched types
    11. --> src/main.rs:10:21
    12. |
    13. 10 | call_fn_pointer(|s| {
    14. | _____________________^
    15. 11 | | println!("{}", outer.len());
    16. 12 | | s.to_string()
    17. 13 | | });
    18. | |_____^ expected fn pointer, found closure
    19. |
    20. = note: expected fn pointer `for<'r> fn(&'r str) -> String`
    21. found closure `[closure@src/main.rs:10:21: 13:6]`
    22. note: closures can only be coerced to `fn` types if they do not capture any variables

    可以看到,如果fn capture了 outter variable, 那么这里就不能用fn pointer了, 必须用Fn三兄弟。

    下面的例子是我碰到的一个比较奇怪的例子,目前还不知道具体原因,但被编译器教育过后知道了 fn 大概率不能用于实现 trait

    1. trait Foo {
    2. fn call(&mut self, msg: &str) -> String;
    3. }
    4. impl Foo for fn(&str) -> String {
    5. fn call(&mut self, msg: &str) -> String {
    6. (*self)(msg)
    7. }
    8. }
    9. fn with_foo<F: Foo>(mut foo: F) -> Option<String> {
    10. let res = foo.call("hello");
    11. Some(res)
    12. }
    13. // so far so good
    14. fn main() {
    15. // 但当我调用with_foo时,编译报错
    16. with_foo(|s: &str| { s.to_string()});
    17. }
    18. error[E0277]: the trait bound `[closure@src/main.rs:11:14: 11:40]: Foo` is not satisfied
    19. --> src/main.rs:11:5
    20. |
    21. 11 | with_foo(|s: &str| { s.to_string()});
    22. | ^^^^^^^^ the trait `Foo` is not implemented for `[closure@src/main.rs:11:14: 11:40]`
    23. |
    24. note: required by a bound in `with_foo`
    25. --> src/main.rs:44:16
    26. |
    27. 44 | fn with_foo<F: Foo>(mut foo: F) -> Option<String> {
    28. | ^^^ required by this bound in `with_foo`

    难道不能用clousure?那我改成函数看看

    1. fn foo(s: &str) -> String {
    2. s.to_string()
    3. }
    4. with_foo(foo);
    5. error[E0277]: the trait bound `for<'r> fn(&'r str) -> String {foo}: Foo` is not satisfied
    6. --> src/main.rs:14:14
    7. |
    8. 14 | with_foo(foo);
    9. | -------- ^^^ the trait `Foo` is not implemented for `for<'r> fn(&'r str) -> String {foo}`
    10. | |
    11. | required by a bound introduced by this call
    12. |

    任然不行。而且报错信息也没有给出明确的问题,换成Fn trait试试

    1. impl<F> Foo for F where F: Fn(&str) -> String {
    2. fn call(&mut self, msg: &str) -> String {
    3. (*self)(msg)
    4. }
    5. }
    6. with_foo(|s: &str| {s.to_string()});

    竟然编译通过了…这里实际上我不太能理解,为什么用fn不可以,而用Fn 是可以编译通过的? 难道trait只能应用在 Fn trait上?但为什么又允许为 fn 实现trait呢?

    1. error[E0119]: conflicting implementations of trait `Foo` for type `for<'r> fn(&'r str) -> std::string::String`
    2. --> src/main.rs:36:1
    3. |
    4. 30 | impl Foo for fn(&str) -> String {
    5. | ------------------------------- first implementation here
    6. ...
    7. 36 | impl<F> Foo for F where F: Fn(&str) -> String {
    8. | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `for<'r> fn(&'r str) -> std::string::String`

    这里还发现个有意思的问题, 这两个impl 不能同时存在, 编译器认为这两个一致?这里让我有些困惑