当迭代器产生新的向量时,冲突的生命周期要求

时间:2015-12-03 00:15:31

标签: rust lifetime borrow-checker

我有一个Grid这样的结构:

pub struct Grid<Item : Copy> {
    raw : Vec<Vec<Item>>
}

我试图在其上重写不同类型的迭代器(主要是作为练习,所以即使有&#34;更好的&#34;解决此处提出的特定问题的方法,我也希望这样做)

迭代行很容易; raw字段只是行的向量,因此每次都可以生成对每个后续行的引用。

但我在迭代列时遇到了困难。我尝试为next()的每次调用构建一个新的Vec,但是引用的寿命不够长 - 这是有道理的。下面的代码是尝试将对临时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>

&#34;帮助&#34; line没有帮助,因为这个建议与特质不相容。

0 个答案:

没有答案