Vortico
Vortico

Reputation: 2749

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

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()`

Upvotes: 41

Views: 18827

Answers (1)

huon
huon

Reputation: 102096

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();

Upvotes: 62

Related Questions