我想将一个结构体的成员函数传递给另一个结构体。
对不起,英语不好,不能说更多细节。
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 ?
};
}
Run Code Online (Sandbox Code Playgroud)
你非常接近!要引用方法或任何其他符号,请使用::分隔符并指定该符号的路径。方法或关联函数位于类型的命名空间中,因此您的方法的路径是Struct1::do_some. 在 Java 中,您还可以使用.运算符来访问它们,但在 Rust 中,.运算符仅用于现有对象,而不用于类型名称。
因此解决方法是:
let s2 = Struct2 {
cb1: Box::new(Struct1::do_some),
};
Run Code Online (Sandbox Code Playgroud)
但是,您可以稍微改进函数的类型。Box<Fn(...)>是一个装箱的 trait 对象,但如果您不想使用闭包,则不一定需要它。如果你只想引用“普通函数”(那些没有环境的函数),你可以使用函数指针:
struct Struct2 {
cb1: fn(&mut Struct1, &str),
}
Run Code Online (Sandbox Code Playgroud)
注意小写fn,我们不需要Box.
| 归档时间: |
|
| 查看次数: |
1691 次 |
| 最近记录: |