我正在尝试将CSV迭代器封装到我的一个结构中:
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
与结构一样长。这显然不是这里发生的事情。