生锈期和所有权:需要一只手

时间:2016-12-08 16:14:52

标签: rust lifetime

我正在尝试将CS​​V迭代器封装到我的一个结构中:

struct PopulationCount {
    city: String,
    country: String,
    count: u64,
}

struct PopulationIter<'a> {
    reader: csv::Reader<std::fs::File>,
    records: DecodedRecords<'a, std::fs::File, Row>,
}

impl<'a> PopulationIter<'a> {
    fn new(file_path: &str, country: &str) -> Result<PopulationIter<'a>, Box<Error>> {
        let file = File::open(file_path)?;
        let mut reader = csv::Reader::from_reader(file);

        let decoded_records = reader.decode::<Row>();

        Ok(PopulationIter {
            reader: reader,
            records: decoded_records,
        })
    }
}

impl<'a> Iterator for PopulationIter<'a> {
    type Item = csv::Result<Row>;

    fn next(&mut self) -> Option<Self::Item> {
        self.records.next()
    }
}

据我了解,DecodedRecords包含对csv::Reader的引用,这就是csv::Reader必须与DecodedRecords一样长的原因。

尝试编译此代码会给我这个错误:

error: `reader` does not live long enough
  --> src/main.rs:39:31
   |
39 |         let decoded_records = reader.decode::<Row>();
   |                               ^^^^^^ does not live long enough
...
42 |     }
   |     - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the block at 34:85...
  --> src/main.rs:34:86
   |
34 |     fn new(file_path: &str, country: &str) -> Result<PopulationIter<'a>, Box<Error>> {
   |                                                                                      ^

我不理解这一点,因为读者被传递给PopulationIter结构,我认为移动语义将适用,使reader与结构一样长。这显然不是这里发生的事情。

0 个答案:

没有答案
相关问题