我有一个Grid
这样的结构:
pub struct Grid<Item : Copy> {
raw : Vec<Vec<Item>>
}
我正在尝试重写不同类型的迭代器(主要是作为练习,所以即使有“更好”的方法来解决这里提出的特定问题,我也想这样做)。
遍历行很容易;该raw
字段只是一个行向量,因此我每次都可以产生对每个后续行的引用。
但是我在遍历列时遇到了困难。我尝试为每次调用构建一个新的 Vec next()
,但引用的寿命不够长 - 这是有道理的。下面的代码是尝试在迭代器结构中存储对临时 vec 的引用,希望能够继承生命周期。但这也不起作用:
pub struct ColIter<'a, T>
where T : 'a + Copy + Debug + Display + FromStr
{
grid : &'a Grid<T>,
index : usize,
col_temp : Vec<T>,
}
impl <'a,T> ColIter<'a,T>
where T : 'a + Copy + Debug + Display + FromStr
{
fn new( grid : &'a Grid<T> ) -> ColIter<'a,T> {
ColIter {
grid : grid,
index : 0,
col_temp : Vec::with_capacity(grid.width()),
}
}
}
impl <'a,T> Iterator for ColIter<'a,T>
where T : Copy + Debug + Display + FromStr
{
type Item = &'a Vec<T>;
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.grid.height() {
for row in 0..self.grid.width() {
self.col_temp[row] = self.grid.raw[row][self.index];
}
self.index += 1;
Some( & self.col_temp ) // <-- ERROR HERE
}
else {
None
}
}
}
这给出了错误:
src/grid.rs:253:19: 253:34 error: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
src/grid.rs:253 Some( & self.col_temp )
^~~~~~~~~~~~~~~
src/grid.rs:247:5: 258:6 help: consider using an explicit lifetime parameter as shown: fn next(&'a mut self) -> Option<Self::Item>
“帮助”行没有帮助,因为该建议与特征不兼容。