我有两个结构体 Foo 和 Bar,我想将一个结构体(Foo)的函数回调存储在另一个结构体(Bar)中,这样它们就不会互相了解。在 Rust 中是否有可能在 Bar 不知道 Foo 存在的情况下(我担心依赖关系)?这是我正在寻找的 C++ 示例
#include <cstdio>
#include <functional>
struct Foo {
void test() {
puts("Test");
}
};
// bar is in another module which shouldn't depend on Foo
// bar doesn't know about foo
template <typename CallbackT>
struct Bar {
Bar(CallbackT callback) :
callback{callback}
{}
void test() {
puts("Doing some stuff...");
callback();
}
CallbackT callback;
};
int main(int argc, const char* argv[]) {
Foo foo;
Bar bar{[&foo]() {
foo.test();
}};
bar.test();
}
是的,你可以在 Rust 中做到这一点。它可以工作并且看起来几乎一样:
struct Foo {}
impl Foo {
fn test(&self) {
println!("Test");
}
}
struct Bar<CallbackT> {
callback: CallbackT,
}
impl<CallbackT> Bar<CallbackT> {
fn new(callback: CallbackT) -> Self {
Bar { callback }
}
fn test(&self) where CallbackT: Fn() {
println!("Doing some stuff...");
(self.callback)();
}
}
fn main() {
let foo = Foo {};
let bar = Bar::new(|| {
foo.test()
});
bar.test();
}