I want to read a file and get back a vector of String
s. 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
&str
per line, which will be thrown away, instead of somehow going straight from the file to aString
per line.
How can this be improved?
As BurntSushi said, you could just use the
lines()
iterator. But, to address your question as-is:You should probably read Error Handling in Rust; those
unwrap()
s should be turned into?
s, with the function's result becoming aResult<Vec<String>, E>
for some reasonableE
. Here, we reuse theio::Result
type alias.Use the
lines()
iterator. The other thing you can do is read the whole file into aString
and return that; there's alines()
iterator for strings as well.This one you can't do anything about:
file_contents
owns its contents, and you can't split them up into multiple, ownedString
s. The only thing you can do is borrow the contents of each line, then convert that into a newString
. That said, the way you've put this implies that you believe creating a&str
is expensive; it isn't. It's literally just computing a pair of offsets and returning those. A&str
slice is effectively equivalent to(*const u8, usize)
.Here's a modified version which does basically the same thing:
One other change I made:
filename
is now a genericP: AsRef<Path>
, because that's whatFile::open
wants, so it will accept more types without needing conversion.