变量在存储csv :: DecodedRecords迭代器时不会足够长 [英] variable does not live long enough when storing a csv::DecodedRecords iterator
问题描述
我试图创建一个迭代器trait,提供特定类型的资源,所以我可以实现多种源类型。我想要创建一个源文件从CSV文件,二进制等读取。
I'm trying to create an iterator trait that provides a specific type of resource, so I can implement multiple source types. I'd like to create a source for reading from a CSV file, a binary etc..
我使用 rust-csv
用于反序列化CSV数据的库:
I'm using the rust-csv
library for deserializing CSV data:
#[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
迭代器的引用:
I cannot seem to store a reference to the DecodedRecords
iterator returned by the CSV reader due to lifetime issues:
错误:读取器不够长时间运行
error: reader does not live long enough
如何存储对解码记录迭代器的引用以及我做错了什么?
How can I store a reference to the decoded records iterator and what am I doing wrong?
推荐答案
根据文档, Reader :: decode
定义为:
According to the documentation, Reader::decode
is defined as:
fn decode<'a, D: Decodable>(&'a mut self) -> DecodedRecords<'a, R, D>
这是 reader.decode()
outlive reader
(因为'a
)。
和这个声明:
That is reader.decode()
cannot outlive reader
(because of 'a
).
And with this declaration:
struct CSVBarSource {
records: csv::DecodedRecords<'static, std::fs::File, BarRecord>,
// ^~~~~~~
}
读者
需要一个'static
生命周期, ,因此它不会因此您得到的错误阅读器
不能居住足够长。
reader
would need a 'static
lifetime, that is it would need to live forever, which it does not hence the error you get "reader
does not live long enough".
直接在
:中读取
CSVBarSource
You should store reader
directly in CSVBarSource
:
struct CSVBarSource {
reader: csv::Reader<std::fs::File>,
}
只需根据需要调用 decode
。
这篇关于变量在存储csv :: DecodedRecords迭代器时不会足够长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!