“预期的 fn 项,发现不同的 fn 项"使用函数指针时 [英] "Expected fn item, found a different fn item" when working with function pointers
问题描述
我有以下代码(Playground):
// Two dummy functions, both with the signature `fn(u32) -> bool`
fn foo(x: u32) -> bool {
x % 2 == 0
}
fn bar(x: u32) -> bool {
x == 27
}
fn call_both<F>(a: F, b: F)
where
F: Fn(u32) -> bool,
{
a(5);
b(5);
}
fn main() {
call_both(foo, bar); // <-- error
}
对我来说,这似乎应该编译为 foo
和 bar
具有相同的签名:fn(u32) ->布尔
.但是,我收到以下错误:
To me, it seems like this should compile as foo
and bar
have the same signature: fn(u32) -> bool
. Yet, I get the following error:
error[E0308]: mismatched types
--> src/main.rs:20:20
|
20 | call_both(foo, bar);
| ^^^ expected fn item, found a different fn item
|
= note: expected type `fn(u32) -> bool {foo}`
found type `fn(u32) -> bool {bar}`
使用此代码可以触发相同的错误:
The same error can be triggered with this code:
let mut x = foo;
x = bar; // <-- error
我还尝试再次将 bar
强制转换为函数指针类型:
I also tried to cast bar
to the function pointer type again:
let mut x = foo;
x = bar as fn(u32) -> bool; // <-- error
这导致了一个稍微不同的错误:
This resulted in a slightly different error:
error[E0308]: mismatched types
--> src/main.rs:20:9
|
20 | x = bar as fn(u32) -> bool;
| ^^^^^^^^^^^^^^^^^^^^^^ expected fn item, found fn pointer
|
= note: expected type `fn(u32) -> bool {foo}`
found type `fn(u32) -> bool`
我完全不明白这些错误.什么是 fn 项与 fn 指针,为什么 foo
和 bar
是不同的 fn 项?
I don't understand these errors at all. What are fn items vs. fn pointers and why are foo
and bar
different fn items?
推荐答案
自 Rust PR #19891 被合并.但是,您可以使用 as
运算符将函数转换为相应的函数指针类型.
Each named function has a distinct type since Rust PR #19891 was merged. You can, however, cast the functions to the corresponding function pointer type with the as
operator.
call_both(foo as fn(u32) -> bool, bar as fn(u32) -> bool);
只转换第一个函数也是有效的:转换将在第二个函数中被推断出来,因为两个函数必须具有相同的类型.
It's also valid to cast only the first of the functions: the cast will be inferred on the second, because both functions must have the same type.
call_both(foo as fn(u32) -> bool, bar);
这篇关于“预期的 fn 项,发现不同的 fn 项"使用函数指针时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!