Newbie question: how do I store an iterator in a struct, and half-way the struct's lifetime, replace that iterator with a new one? My test program, takes a vec of strings, and wraps that in a CharStream (or CharIterator or CharGenerator - whatever you want to call it). Goal is to do this without transforming or copying the original data, so no concat or map() or collect() into an intermediate list of some sorts.
use core::str::Chars;
struct CharStream<'a> {
stream: std::vec::Vec<String>, //test data
line: usize, //test data
char_it: Chars<'a>
}
impl<'a> CharStream<'a> {
fn new(stream: std::vec::Vec<String>) -> CharStream<'a> {
CharStream { stream: stream, line: 0, char_it: stream[0].chars()}
}
/// next() should give the next char in the 'stream'.
/// to keep the function simple, it just returns the first char of each line...
/// and tries to replace the chars iterator with the next one.
fn next(&mut self) -> Option<char> {
self.line += 1;
self.char_it = self.stream[self.line].chars(); //<< this fails!
self.char_it.next()
}
}
fn main() {
//just test data, imagine some stream, read line by line:
let mut stream = Vec::new();
stream.push("initial".to_string());
stream.push("second".to_string());
stream.push("third".to_string());
let mut cont = CharStream::new(stream);
for i in 0..1 {
let c = cont.next();
println!("{:?}", c);
}
}
If possible, I'm looking for the smallest fix to this code, but if in Rust, another pattern is better to implement this... The goal remains to be able to generate one stream from another without intermediate storage or full consumption of the incoming stream.