Cannot infer type

fn foo<F, G>(f: F, g: G)
where
    F: Fn(i32, G) -> i32,
    G: Fn(i32) -> i32
{
    println!{"f(32) = {}", f(32, g)};
}


fn main() {

    foo(|x, f| f(x + 32), |x| x * x)
}
error[E0282]: type annotations needed
  --> src/main.rs:12:16
   |
12 |     foo(|x, f| f(x + 32), |x| x * x)
   |                ^^^^^^^^^ cannot infer type
   |
   = note: type must be known at this point

why rust cannot infer type

1 Like

I think it is a bug.

You should probably leave an issue on Rust GitHub.

I've managed to make your code working:

foo(|x, f: fn(i32) -> i32| f(x + 32), |x| x * x)

But this error is not intended to be here so it is probably a type inference bug.

thank you

This doesn't look like a bug. The type signature for foo requires that the first arg satisfies two constraints, but the closure itself does not prove the second constraint. (which is why your suggestion works; it proves the second constraint).

Rust only does local type inference; it will not infer types based on the closure body. The types must be known in the signature.

Here's another alternative. While it may not be as pretty, it shows that type inference works locally:

type MyFn = fn(i32) -> i32;

fn bar<F>(f: F, g: MyFn)
where
    F: Fn(i32, MyFn) -> i32,
{
    println!{"f(32) = {}", f(32, g)};
}

fn main() {
    bar(|x, f| f(x + 32), |x| x * x)
}

playground

1 Like