I want to pass a member function of a struct to another struct.
Sorry, poor English, can't say more details.
use std::thread;
struct Struct1 {}
impl Struct1 {
pub fn do_some(&mut self, s: &str) {
// do something use s to 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 to store do_some function in cb1 ?
};
}
You were very close! To refer to a method or any other symbol you use the
::
separator and specify the path to said symbol. Methods or associated functions live in the namespace of the type, therefore the path of your method isStruct1::do_some
. In Java you would also use the.
operator to access those, but in Rust the.
operator is only used on existing objects, not on type names.The solution thus is:
However, you could possibly improve the type of your function a bit.
Box<Fn(...)>
is a boxed trait object, but you don't necessarily need that if you don't want to work with closures. If you just want to refer to "normal functions" (those who don't have an environment), you can use a function pointer instead:Note the lowercase
fn
and that we don't need theBox
.