2016-04-15 57 views
1

我想创建一个提供特定类型的资源的迭代器特征,所以我可以实现多种源类型。我想创建一个源从一个CSV文件中读取,二进制等。变量不够长,当存储csv :: DecodedRecords迭代器

我使用rust-csv库解串CSV数据:

#[derive(RustcDecodable)] 
struct BarRecord { 
    bar: u32 
} 

trait BarSource : Iterator {} 

struct CSVBarSource { 
    records: csv::DecodedRecords<'static, std::fs::File, BarRecord>, 
} 

impl CSVBarSource { 
    pub fn new(path: String) -> Option<CSVBarSource> { 
     match csv::Reader::from_file(path) { 
      Ok(reader) => Some(CSVBarSource { records: reader.decode() }), 
      Err(_) => None 
     } 
    } 
} 

impl Iterator for CSVBarSource { 
    type Item = BarRecord; 

    fn next(&mut self) -> Option<BarRecord> { 
     match self.records.next() { 
      Some(Ok(e)) => Some(e), 
      _ => None 
     } 
    } 
} 

我似乎无法存储参考通过CSV读者由于寿命问题返回DecodedRecords迭代器:

error: reader does not live long enough

我怎样才能存到解码记录迭代器的引用,我究竟做错了什么?

回答

2

根据该文件,Reader::decode is defined as

fn decode<'a, D: Decodable>(&'a mut self) -> DecodedRecords<'a, R, D> 

也就是说reader.decode()不能活得比reader(因为'a)。 而与此声明:

struct CSVBarSource { 
    records: csv::DecodedRecords<'static, std::fs::File, BarRecord>, 
           // ^~~~~~~ 
} 

reader需要一个'static一生,那就是它需要永远活着,它并没有因此得到错误“reader不活足够长的时间”。

你应该CSVBarSource直接存储reader

struct CSVBarSource { 
    reader: csv::Reader<std::fs::File>, 
} 

并调用decode只在需要。

+0

感谢您的明确解释! –