0
点赞
收藏
分享

微信扫一扫

Closure as the function parameter

骑在牛背上看书 2022-03-18 阅读 81

Closure as the function parameter

(Jin Qing’s Column, Mar., 2022)

It is best to let the function take a closure trait as the parameter instead of a function pointer.

fn foo(f: fn()) {
    f()
}

fn main() {
    foo(|| println!("hello"));
    let a = 123;
    foo(move || println!("{}", a))
}

compiles error:

error[E0308]: mismatched types
 --> src/main.rs:9:9
  |
9 |     foo(move || println!("{}", a))
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^ expected fn pointer, found closure
  |
  = note: expected fn pointer `fn()`
                found closure `[closure@src/main.rs:9:9: 9:34]`
note: closures can only be coerced to `fn` types if they do not capture any variables
 --> src/main.rs:9:32
  |
9 |     foo(move || println!("{}", a))
  |                                ^ `a` captured here

For more information about this error, try `rustc --explain E0308`.

https://doc.rust-lang.org/book/ch19-05-advanced-functions-and-closures.html

举报

相关推荐

0 条评论