更清楚的方法将文件的内容作为字符串在Rust中?

Ear*_*rlz 9 file-io rust

作为我第一次潜入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喜欢放在前面和中心的东西.

  • @hauleth这是一个非常严格的声明.您是否对"恐慌","无法访问"或"断言"提出同样的主张?所有这些都会导致线程恐慌.在生产代码中有很多理由要"恐慌".具体来说,我声明编码**逻辑错误***应该*在遇到时引起恐慌.当然,此示例不是生产代码,处理错误情况取决于示例的用户和该应用程序的上下文. (2认同)