当我尝试编译以下代码时:
fn main() {
(...)
let mut should_end = false;
let mut input = Input::new(ctx);
input.add_handler(Box::new(|evt| {
match evt {
&Event::Quit{..} => {
should_end = true;
}
_ => {}
}
}));
while !should_end {
input.handle();
}
}
pub struct Input {
handlers: Vec<Box<FnMut(i32)>>,
}
impl Input {
pub fn new() -> Self {
Input {handlers: Vec::new()}
}
pub fn handle(&mut self) {
for a in vec![21,0,3,12,1] {
for handler in &mut self.handlers {
handler(a);
}
}
}
pub fn add_handler(&mut self, handler: Box<FnMut(i32)>) {
self.handlers.push(handler);
}
}
我遇到了这个错误:
error: closure may outlive the current function, but it borrows `should_end`, which is owned by the current function
我不能简单地将move
添加到闭包中,因为我需要在主循环中稍后使用should_end
。我的意思是,我可以这样做,但由于bool
是Copy
,它只会影响闭包内部的should_end
,因此程序会一直循环。
据我所知,由于input
是在主函数中创建的,并且闭包存储在input
中,它不可能超出当前函数的生命周期。有没有办法向Rust表达闭包不会超出main
的生命周期?或者我可能看不到闭包将超出main
的生命周期吗?在后一种情况下,有没有办法强制其仅存在于main
的生命周期中?
我需要重新处理输入的方式吗,还是有办法使其工作。如果需要重新处理,则可以在Rust中查看哪些示例?
这里是简化版本的Playpen。我可能犯了一个错误,可能会导致浏览器崩溃。我曾经遇到过这样的情况,所以要小心。
如果需要,其余的代码都可用。所有相关信息应该在main.rs
或input.rs
中。
Cell
等内容的资料。除此之外,非常详尽的答案,谢谢。 - MrNosco'static
是从哪里来的,有没有记录在某个地方? - starblue'b: 'a
而不是只写成'b
呢?这个限制的理论基础是什么? - Nawaz