How to pass a member function of a struct to anoth

2019-07-29 07:15发布

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 ?
    };
}

标签: rust
1条回答
萌系小妹纸
2楼-- · 2019-07-29 07:52

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 is Struct1::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:

let s2 = Struct2 {
    cb1: Box::new(Struct1::do_some),
};

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:

struct Struct2 {
    cb1: fn(&mut Struct1, &str),
}

Note the lowercase fn and that we don't need the Box.

查看更多
登录 后发表回答