作为我第一次潜入Rust的一段时间,我开始编写代码将文件的内容转储到字符串中,以便以后处理(现在我只是打印出来)
有没有比我现在更清洁的方法呢?看起来我不得不对它过于冗长,但我没有看到任何好的方法来清理它
use std::io;
use std::io::File;
use std::os;
use std::str;
fn main() {
println!("meh");
let filename = &os::args()[1];
let contents = match File::open(&Path::new(filename)).read_to_end() {
Ok(s) => str::from_utf8(s.as_slice()).expect("this shouldn't happen").to_string(),
Err(e) => "".to_string(),
};
println!("ugh {}", contents.to_string());
}
Run Code Online (Sandbox Code Playgroud)
She*_*ter 15
编者注:使用更短/更清晰的答案,查看维护答案的链接副本.
Read::read_to_string 是我所知道的最短的:
use std::io::prelude::*;
use std::fs::File;
fn main() {
let mut file = File::open("/etc/hosts").expect("Unable to open the file");
let mut contents = String::new();
file.read_to_string(&mut contents).expect("Unable to read the file");
println!("{}", contents);
}
Run Code Online (Sandbox Code Playgroud)
必须考虑失败案例是Rust喜欢放在前面和中心的东西.