I'm currently studying Rust Language by practice. My new challenge is to use store implement
Iterator Trait
to my data structure which role is to use an internal iterator over a Vec<String>
:
impl<'a> CSVReader<'a> {
pub fn new(lines: Vec<String>, nb_labels: u32, labels: Vec<String>, delim: char) -> Self {
CSVReader {
lines,
iter: None,
delim,
nb_labels,
labels
}
}
fn update_iter(&'a mut self) {
match &self.iter {
Some(_) => (),
None => { self.iter = Some(self.lines.iter()) }
};
}
// ...
}
impl<'a> Iterator for CSVReader<'a> {
type Item = Vec<String>;
fn next(&mut self) -> Option<Self::Item> {
self.update_iter(); // ------- line 66
let line: String;
if let Some(iter) = &mut self.iter {
line = iter.next()?.clone();
let cols: Vec<String> = line
.split(self.delim)
.map(|x| x.to_string())
.collect();
Some(cols)
} else {
None
}
}
}
This code does not compile due to this error:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/csv_parser/reader.rs:66:14
|
66 | self.update_iter();
I tried to add lifetime precision on the implementation of Iterator Trait
but I get another error asking me to work with the right prototype of next()
function.
I wish you could help me to understand why it doesn't work and provide some solutions to solve it :)