我有一个 Rust 结构:
pub struct Application {
name: String,
windows: Vec<Window>,
event_loop: EventLoop<()>,
}
在这里,我有一个方法可以移动自身并运行一个需要移动闭包的事件循环。我仍然想引用 self,因为它有一些我需要根据事件运行的方法。看起来像这样
pub fn run(mut self) {
self.event_loop.run(move |event, _, control_flow| match event {
Event::WindowEvent {
window_id,
..
} => {
&self.send_event_to_window(window_id, event);
},
Event::RedrawRequested(window_id) => {
&self.send_event_to_window(window_id, event);
}
Event::MainEventsCleared => {
// RedrawRequested will only trigger once, unless we manually
// request it.
// state.window().request_redraw();
}
_ => {},
});
}
rust 对我使用 self.send_event_to_window 有问题并说 “使用部分移动的值:
self
”
如何从这个闭包中访问 self ?我什至不确定为什么当我将它移入封闭物时,生锈不允许我使用它。
当您在
self.eventLoop.run
中写入 Application.run
时,EventLoop.run
拥有 self.eventLoop
的所有权(self
的部分所有权)。因此,闭包无法调用 self
上的任何方法,因为这样的方法可能会使用 self.eventLoop
。
有几种方法可以解决这个问题:
event_loop
设为 run
函数中的局部变量event_loop
作为 run
函数的参数event_loop
所需的变量放入单独的结构中,如下所示:pub struct ApplicationState {
name: String,
windows: Vec<Window>,
// put anything that needs to be accessible by the run closure here
}
impl ApplicationState {
// implement functions that do not use event_loop here
// these can be called by the run closure
fn send_event_to_window(window_id, event) {}
}
pub struct Application {
state: ApplicationState,
event_loop: EventLoop<()>,
}
impl Application {
pub fn run(mut self) {
self.event_loop.run(move |event, _, control_flow| match event {
Event::WindowEvent {
window_id,
..
} => {
&self.state.send_event_to_window(window_id, event);
},
Event::RedrawRequested(window_id) => {
&self.state.send_event_to_window(window_id, event);
}
Event::MainEventsCleared => {
// RedrawRequested will only trigger once, unless we manually
// request it.
// state.window().request_redraw();
}
_ => {},
});
}
}