Can't use trait on function pointer

Viewed 105

When I try to call a trait method on a function pointer:

trait Foo {
    fn do_it(&self, i: i32);
}

impl Foo for fn(i32) {
    fn do_it(&self, i: i32) {
        self(i)
    }
}

fn bar(i: i32) {}
fn baz() {
    bar.do_it(7);
}

The compiler says no method named 'do_it' found for fn item 'fn(i32) {bar}' in the current scope ... note: 'Foo' defines an item 'do_it', perhaps you need to implement it.

What's wrong with my implementation?

1 Answers

You need to impl Foo on a trait object, instead of trying to access the fn() type. By declaring that you want to implement Foo for any object F which has already implemented the Fn(i32) trait, the compiler then recognizes that there is a method associated with that type of function.

I added main() to be able to view output and verify it worked as expected.

trait Foo {
    fn do_it(&self, i: i32);
}

impl<F> Foo for F where F: Fn(i32) {
    fn do_it(&self, i: i32) {
        self(i)
    }
}

fn bar(i: i32) {
    println!("{}", i);
}

fn main() {
    bar.do_it(7);
}
Related