我在试着制作一个类似"回调系统"的东西.例如,有一个窗口和几个按钮.该窗口 for each 按钮设置回调.两个回调都应该更改窗口的状态.编译器不允许在我的闭包/回调中捕获&self
个,我不知道如何使其工作.
我应该遵循哪些常见的回调模式?
这是一个简单的例子,因为所有组件都有相同的生命周期 .如果组件的使用生命周期 不同呢?
struct Button<'a> {
f: Option<Box<Fn() + 'a>>,
}
impl<'a> Button<'a> {
fn new() -> Button<'a> { Button { f: None } }
fn set<T: Fn() + 'a>(&mut self, f: T) { self.f = Some(Box::new(f)); }
fn unset(&mut self) { self.f = None; }
fn call(&self) { match self.f { Some(ref f) => f(), None => () } }
}
struct Window<'a> {
btn: Button<'a>,
//btns: Vec<Button<'a>>,
}
impl<'a> Window<'a> {
fn new() -> Window<'a> {
Window { btn: Button::new() }
}
fn hi(&mut self) { // self is mutable
println!("callback");
}
fn run(&mut self) {
// Compile error: cannot infer an appropriate lifetime for
// capture of `self` by closure due to conflicting requirements
self.btn.set(|| self.hi()); // How to make it work?
self.btn.call();
self.btn.unset();
}
}
fn main() {
let mut wnd = Window::new();
wnd.run();
}