"Expected element fn, another element fn detected" when working with function pointers

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;  // <-- error

I also tried to cast the type barto a function pointer type again:

let mut x = foo;
x = bar as fn(u32) -> bool;  // <-- error

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?

+8
source share
2 answers

Rust PR # 19891. as.

call_both(foo as fn(u32) -> bool, bar as fn(u32) -> bool);

: , .

call_both(foo as fn(u32) -> bool, bar);
+11

, , , (, fn(u32) → bool). (, fn(u32) → bool {foo}).

, . , . , . , : .

; .

, : let _: fn(u32) → bool = foo; . , : foo as fn(u32) → bool.

, .



, , foo bar . call_both(foo, bar) F fn(u32) → bool {foo}, . , .

, F:

call_both::<fn(u32) -> bool>(foo, bar);
call_both::<fn(_) -> _>(foo, bar);       // <-- even this works

. , as -cast fn(u32) → bool .

, :

let mut x: fn(u32) -> bool = foo;
x = bar;

: -, , .

+4

Source: https://habr.com/ru/post/1570820/


All Articles