2

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 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

"You need to impl Foo on a trait object" - they don't, and that's not what you do in your own code - there's no dyn Fn here. This is so-called "blanket implementation" - doc.rust-lang.org/book/….
Using a blanket implementation prevents me from implementing the trait on more than one type of function pointer, since they conflict.
Yeah, that may just be a limitation of Rust's strong typing... you'd need to repeat your impl block for every type, the same way you'd need to repeat an impl for every int type (i8, u8, i16...), although it probably could be shortened with a macro.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.