Implement trait bound for `fn`

Is it possible to implement a trait for a specific function and not all T that implements Fn. Something like this:

trait Function {}

fn a(x: i32) {}
impl Function for fn(i32) {}

fn func<F: Function>(f: F) {}

fn main() {

This fails with:

error[E0277]: the trait bound `fn(i32) {a}: Function` is not satisfied
 --> examples/
9 |     func(a);
  |     ---- ^ the trait `Function` is not implemented for `fn(i32) {a}`
  |     |
  |     required by a bound introduced by this call
  = help: the following implementations were found:
            <fn(i32) as Function>

But trying to do:

impl Function for fn(i32) {a} {}

is also incorrect.

You may want to try a blanket implementation:

trait Function {}
impl<F: Fn(u32)> Function for F {}

Or you may want to use F: Fn(u32) directly.

The issue you're facing is that each function gets its own type, so that when it gets passed into a generic function it can be inlined if necessary.

I just saw that you specified "not for all T which impl Fn" and the issue is that you cannot refer to function types directly. Instead, you could coerce the function into a function pointer with as fn(u32).

1 Like