Why is type annotation needed when type is explicit as `Self` in generic bound?

⚓ Rust    📅 2025-12-20    👤 surdeus    👁️ 1      

surdeus

Given the following code:

trait A: Sized {
    fn fn_to_fn<Fn0, Fn1>(self, f: Fn0) -> ()
    where
        Fn0: Fn() -> Option<Fn1>,
        Fn1: Fn(&mut Self),
    {
        ()
    }
}

impl<T> A for T {}

fn a() {
    let integer = 0u32;
    integer.fn_to_fn(|| Some(|mut integer| *integer += 1));
}

I get the following error:

error[E0282]: type annotations needed
  --> src/lib.rs:81:31
   |
81 |     integer.fn_to_fn(|| Some(|mut integer| *integer += 1));
   |                               ^^^^^^^^^^^  -------- type must be known at this point
   |
help: consider giving this closure parameter an explicit type
   |
81 |     integer.fn_to_fn(|| Some(|mut integer: /* Type */| *integer += 1));
   |                                          ++++++++++++

I don't understand why type annotation is needed when Fn1 is explicit as implementing Fn(&mut Self). Even my IDE identifies the type of integer within the F1 enclosure as &mut u32, however the compiler needs me to annotate the type. Can someone explain why this is the case, and if possible, suggest how I can avoid type annotation?

One additional observation is that replacing the return type of F0 (Option<F1>) with just F1 no longer needs type annotation...

1 post - 1 participant

Read full topic

🏷️ Rust_feed