I have the following code ( 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
}
I think it should compile as fooand barhave the same signature: fn(u32) → bool. However, 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 caused by this code:
let mut x = foo;
x = bar;
I also tried to cast the type barto a function pointer type again:
let mut x = foo;
x = bar as fn(u32) -> bool;
This led to 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'
I do not understand these errors at all. What is fn items and fn pointers and why foo, and bardiffer from fn items?
source
share