So discovered BufRead.read_line(), but need an iterator of &str
, want to avoid the overhead of allocating a new string on every iteration of BufRead.lines().
Thought I could make a “simple” iterator wrapper for BufRead:
struct BufLines<'a> {
src: &'a mut BufRead,
buf: String,
err: Option<io::Error>,
}
impl<'a> Iterator for BufLines<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
self.buf.clear();
let r = self.src.read_line(&mut self.buf);
match r {
Ok(bytes) => {
match bytes {
0 => None,
_ => Some(&self.buf),
}
}
Err(e) => {
self.err = Some(e);
None
}
}
}
}
However, the compiler disagrees:
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> manifest/mod.rs:145:14
|
145 | Some(&self.buf)
| ^^^^^^^^^
|
help: consider using an explicit lifetime parameter as shown: fn get(&'a self) -> Option<&'a str>
--> manifest/mod.rs:144:5
|
144 | fn get(&self) -> Option<&'a str> {
| ^
I don’t know what the conflicting requirements are here since the compiler won’t tell me, and the advice it provides only leads to more confusion.
Is there another way to create this iterator that I’ve missed? Is there already one in the standard library?
Ideas for a workaround?
Thanks.