I am trying to iterate over characters in stdin. The Read.chars()
method achieves this goal, but is unstable. The obvious alternative is to use Read.lines()
with a flat_map
to convert it to a character iterator.
This seems like it should work, but doesn't, resulting in borrowed value does not live long enough
errors.
use std::io::BufRead;
fn main() {
let stdin = std::io::stdin();
let mut lines = stdin.lock().lines();
let mut chars = lines.flat_map(|x| x.unwrap().chars());
}
This is mentioned in Read file character-by-character in Rust, but it does't really explain why.
What I am particularly confused about is how this differs from the example in the documentation for flat_map
, which uses flat_map
to apply .chars()
to a vector of strings. I don't really see how that should be any different. The main difference I see is that my code needs to call unwrap()
as well, but changing the last line to the following does not work either:
let mut chars = lines.map(|x| x.unwrap());
let mut chars = chars.flat_map(|x| x.chars());
It fails on the second line, so the issue doesn't appear to be the unwrap
.
Why does this last line not work, when the very similar line in the documentation doesn't? Is there any way to get this to work?