Read file character-by-character in Rust

后端 未结 2 508
梦毁少年i
梦毁少年i 2020-12-17 14:28

Is there an idiomatic way to process a file one character at a time in Rust?

This seems to be roughly what I\'m after:

let mut f = io::BufReader::new         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-17 15:10

    There are two solutions that make sense here.

    First, you could copy the implementation of Read::chars() and use it; that would make it completely trivial to move your code over to the standard library implementation if/when it stabilizes.

    On the other hand, you could simply iterate line by line (using f.lines()) and then use line.chars() on each line to get the chars. This is a little more hacky, but it will definitely work.

    If you only wanted one loop, you could use flat_map() with a lambda like |line| line.chars().

提交回复
热议问题