如何设置盒装闭包捕获“self”的生命周期?
How to set lifetime for boxed closure capturing `self`?
我想要 return 一个迭代器(特别是 Filter
)。我使用了一个 previous answer 来建议 returning 一个盒装迭代器。问题是我的过滤器捕获了 self
并且我得到:
error: closure may outlive the current function, but it borrows self
, which is owned by the current function
但我想我明确表示 self
有生命周期 'a
并且 Box
也有生命周期 returning:
fn occupied_iter_x<'a>(&'a self) -> Box<Iterator<Item=i32> + 'a> {
Box::new( (0..32).filter( |&pos| match self.at(pos) { Occupied::Empty => false, _ => true } ) )
}
这是为了简化我的第一个工作,我创建了一个新的 FooIterator
,它以基本相同的方式拥有对 self
的引用。
如果我使用大部分相同的语法来简单地捕获 self
作为成员引用,它工作正常:
struct Foo { junk: i32 }
struct FooIterator<'a> { foo: &'a Foo }
impl Foo {
fn foo<'a>(&'a self) -> Box<FooIterator<'a>> {
Box::new( FooIterator { foo: self } )
}
}
您收到错误是因为您的闭包接收到对 self
的引用,它本身就是一个引用。但是,由于引用指向一个局部变量,一旦函数returns.
,该引用就失效了。
要解决此问题,请在闭包前添加 move
关键字。这指示编译器 移动 闭包中的 closed-over 变量,而不是 将对这些变量的引用 传递给闭包。
fn occupied_iter_x<'a>(&'a self) -> Box<Iterator<Item=i32> + 'a> {
Box::new( (0..32).filter(move |&pos| match self.at(pos) { Occupied::Empty => false, _ => true } ) )
}
我想要 return 一个迭代器(特别是 Filter
)。我使用了一个 previous answer 来建议 returning 一个盒装迭代器。问题是我的过滤器捕获了 self
并且我得到:
error: closure may outlive the current function, but it borrows
self
, which is owned by the current function
但我想我明确表示 self
有生命周期 'a
并且 Box
也有生命周期 returning:
fn occupied_iter_x<'a>(&'a self) -> Box<Iterator<Item=i32> + 'a> {
Box::new( (0..32).filter( |&pos| match self.at(pos) { Occupied::Empty => false, _ => true } ) )
}
这是为了简化我的第一个工作,我创建了一个新的 FooIterator
,它以基本相同的方式拥有对 self
的引用。
如果我使用大部分相同的语法来简单地捕获 self
作为成员引用,它工作正常:
struct Foo { junk: i32 }
struct FooIterator<'a> { foo: &'a Foo }
impl Foo {
fn foo<'a>(&'a self) -> Box<FooIterator<'a>> {
Box::new( FooIterator { foo: self } )
}
}
您收到错误是因为您的闭包接收到对 self
的引用,它本身就是一个引用。但是,由于引用指向一个局部变量,一旦函数returns.
要解决此问题,请在闭包前添加 move
关键字。这指示编译器 移动 闭包中的 closed-over 变量,而不是 将对这些变量的引用 传递给闭包。
fn occupied_iter_x<'a>(&'a self) -> Box<Iterator<Item=i32> + 'a> {
Box::new( (0..32).filter(move |&pos| match self.at(pos) { Occupied::Empty => false, _ => true } ) )
}