I want to read a file and get back a vector of Strings. The following function works, but is there a more concise or idiomatic way?
use std::fs::File;
use std::io::Read;
fn lines_from_file(filename: &str) -> Vec<String> {
let mut file = match File::open(filename) {
Ok(file) => file,
Err(_) => panic!("no such file"),
};
let mut file_contents = String::new();
file.read_to_string(&mut file_contents)
.ok()
.expect("failed to read!");
let lines: Vec<String> = file_contents.split("\n")
.map(|s: &str| s.to_string())
.collect();
lines
}
Some things that seem suboptimal to me:
- Two separate error checks for reading the file.
- Reading the entire file to a
String, which will be thrown away. This would be particularly wasteful if I only wanted the first N lines. - Making a
&strper line, which will be thrown away, instead of somehow going straight from the file to aStringper line.
How can this be improved?
lines()iterator: doc.rust-lang.org/std/io/trait.BufRead.html#method.linesidiomatictag be removed, since it exactly describes the kind of thing I'm asking about.