Define `fn` type for methods that take `self: Foo<'a>`

⚓ Rust    📅 2026-01-20    👤 surdeus    👁️ 14      

surdeus

Warning

This post was published 50 days ago. The information described in this article may have changed.

Can you help me figure out how to define an fn type that can take values of method type?

struct Foo<'a>(&'a u32);

impl<'a> Foo<'a> {
    fn bar(&mut self) {
        type Func = fn(&mut Foo); // Same error with this
        //type Func = for<'b> fn(&'b mut Foo<'_>); // Same error with this
        let f: Func = Foo::baz;
        f(self)
    }
    
    fn baz(&mut self) {}
}
error[E0308]: mismatched types
 --> src/main.rs:7:23
  |
7 |         let f: Func = Foo::baz;
  |                ----   ^^^^^^^^ one type is more general than the other
  |                |
  |                expected due to this
  |
  = note: expected fn pointer `for<'a, 'b> fn(&'a mut Foo<'b>)`
                found fn item `for<'a> fn(&'a mut Foo<'_>) {Foo::<'_>::baz}`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Playground

The complicating factor here happens to be that the self type has a lifetime parameter, and the Funcs above are interpreted as for<'a, 'b> fn(&'a mut Foo<'b>).

In addition to the solution, I'd appreciate an understanding of the problem and the precise distinction the compiler is making.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed