rust - How to pass a member function of a struct to another struct as callback -
i want pass member function of struct struct.
sorry, poor english, can't more details.
use std::thread; struct struct1 {} impl struct1 { pub fn do_some(&mut self, s: &str) { // use s modify self } } struct struct2 { cb1: box<fn(&mut struct1, &str)>, } fn main() { let s1 = struct1 {}; let s2 = struct2 { cb1: box::new(s1.do_some), // how store do_some function in cb1 ? }; }
you close! refer method or other symbol use ::
separator , specify path said symbol. methods or associated functions live in namespace of type, therefore path of method struct1::do_some
. in java use .
operator access those, in rust .
operator used on existing objects, not on type names.
the solution is:
let s2 = struct2 { cb1: box::new(struct1::do_some), };
however, possibly improve type of function bit. box<fn(...)>
boxed trait object, don't need if don't want work closures. if want refer "normal functions" (those don't have environment), can use function pointer instead:
struct struct2 { cb1: fn(&mut struct1, &str), }
note lowercase fn
, don't need box
.
Comments
Post a Comment