Is there a way to create a function pointer to a method in Rust?

rust

Solution

With fully-qualified syntax, `Foo::bar` will work, yielding a `fn(&Foo) -> ()` (similar to Python).

let callback = Foo::bar;
// called like
callback(&foo);

However, if you want it with the `self` variable already bound (as in, calling `callback()` will be the same as calling `bar` on the `foo` object), then you need to use an explicit closure:

let callback = || foo.bar();
// called like
callback();

Problem

For example, ``` struct Foo; impl Foo { fn bar(&self) {} fn baz(&self) {} } fn main() { let foo = Foo; let callback = foo.bar; } ``` ``` error[E0615]: attempted to take value of method `bar` on type `Foo` --> src/main.rs:10:24 | 10 | let callback = foo.bar; | ^^^ help: use parentheses to call the method: `bar()` ```

Original source