我正在尝试在一个二维网格上实现一个迭代器,如下所示(这是一个稍微复杂的设置的简化):
struct Grid {
width: usize,
height: usize,
}
impl Grid {
fn new(width: usize, height: usize) -> Grid {
Grid { width, height }
}
fn iter<'a>(&'a self) -> &'a impl Iterator<Item = (usize, usize)> {
let i = (0..self.height).flat_map(|y: usize| (0..self.width).map(move |x| (x, y)));
&i
}
}error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/lib.rs:12:43
|
12 | let i = (0..self.height).flat_map(|y: usize| (0..self.width).map(move |x| (x, y)));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime 'a as defined on the method body at 11:13...
--> src/lib.rs:11:13
|
11 | fn iter<'a>(&'a self) -> &'a impl Iterator<Item = (usize, usize)> {
| ^^
= note: ...so that the types are compatible:
expected &&Grid
found &&'a Grid
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that return value is valid for the call
--> src/lib.rs:11:34
|
11 | fn iter<'a>(&'a self) -> &'a impl Iterator<Item = (usize, usize)> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^我不知道如何向迭代器返回一个适当的生命周期引用。我知道迭代器的生命周期不能超过底层Grid结构的生命周期。
发布于 2018-12-06 18:07:16
返回类型不能是引用。诀窍是为返回类型添加生存期说明符。此外,这两个闭包都需要有move来获取self和y的所有权。
fn iter<'a>(&'a self) -> impl Iterator<Item = (usize, usize)> + 'a {
(0..self.height).flat_map(move |y| (0..self.width).map(move |x| (x, y)))
}发布于 2018-12-06 22:34:11
这里没有理由维护对原始结构的任何引用,因为所有的封闭值都实现了Copy。您只需要从结构中提取height和width,并在执行此操作时制作一个副本:
fn iter(&self) -> impl Iterator<Item = (usize, usize)> {
let Self { height, width } = *self;
(0..height).flat_map(move |y| (0..width).map(move |x| (x, y)))
}https://stackoverflow.com/questions/53648396
复制相似问题