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()' 
+10
rust
source share
1 answer

With fully defined syntax, Foo::bar will work, resulting in fn(&Foo) ->() (similar to Python); if this is what you want (i.e. call it as callback(&foo) ):

 let callback = Foo::bar; 

However, if you want the self variable to be already bound (like, for example, callback() will be the same as calling bar for the foo object), you need to use an explicit closure

 let callback = || foo.bar(); 
+17
source share

All Articles