Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
77 views
in Technique[技术] by (71.8m points)

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()`
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...