I'm trying to create a constructor for my struct, which would store an iterator over String
read from file. The problem is that once the functions returns, String
is dropped and compiler complains new() returns a value referencing data owned by the current function
. Is there a way to associate String
with a struct somehow so that it is not dropped after return?
I think I understand a complaint here but I don't understand how to deal with it, because I want constructor to deal both with file reading and iterator creation.
pub struct CharStream<'a> {
input: std::str::Chars<'a>,
filename: String,
}
impl<'a> CharStream<'a> {
pub fn new(filename: String) -> CharStream<'a> {
let mut file = File::open(&filename).unwrap();
let mut input = String::new();
file.read_to_string(&mut input);
CharStream {
input: input.chars(), // Create an iterator over `input`
filename: filename,
}
// `input` is dropped here
}
}