我有以下代码(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) -> bool
.然而,我得到了以下错误:
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}`
此代码可能会触发相同的错误:
let mut x = foo;
x = bar; // <-- error
我还try 再次将bar
转换为函数指针类型:
let mut x = foo;
x = bar as fn(u32) -> bool; // <-- 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`
我完全不理解这些错误.What are fn items vs. fn pointers and why are 100 and 101 different fn items?