gpt4 book ai didi

rust - 为什么将闭包传递给接受函数指针的函数不起作用?

转载 作者:行者123 更新时间:2023-11-29 07:43:02 25 4
gpt4 key购买 nike

second edition of The Rust Programming Language (强调我的):

Function pointers implement all three of the closure traits (Fn, FnMut, and FnOnce), so you can always pass a function pointer as an argument for a function that expects a closure. It’s best to write functions using a generic type and one of the closure traits so your functions can accept either functions or closures.

将闭包传递给接受函数指针作为参数的函数不会编译:

fn main() {
let a = String::from("abc");

let x = || println!("{}", a);

fn wrap(c: fn() -> ()) -> () {
c()
}

wrap(x);
}
error[E0308]: mismatched types
--> src/main.rs:10:10
|
10 | wrap(x);
| ^ expected fn pointer, found closure
|
= note: expected type `fn()`
found type `[closure@src/main.rs:4:13: 4:33 a:_]`

为什么这不起作用?

最佳答案

闭包不是函数。

您可以将一个函数传递给一个需要闭包的函数,但没有理由反之亦然。

如果您希望能够将闭包和函数都作为参数传递,只需为闭包做好准备即可。

例如:

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

关于rust - 为什么将闭包传递给接受函数指针的函数不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52696907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com