【问题标题】:Cleaner way to get the contents of a file as string in Rust? [duplicate]在 Rust 中以字符串形式获取文件内容的更简洁方法? [复制]
【发布时间】:2014-12-14 22:33:49
【问题描述】:

在我第一次接触 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());
}

【问题讨论】:

    标签: file-io rust


    【解决方案1】:

    编者注:查看the linked duplicate 以获得更短/更清晰的答案。

    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);
    }
    

    Rust 喜欢将失败案例放在首位。

    【讨论】:

    • 你不应该在生产代码中使用unwrapmatchmapand_then
    • @hauleth 这是一个非常严格的声明。您是否对panicunreachableassert 提出相同的要求?所有这些都会产生线程恐慌。在生产代码中panic 有很多理由。具体来说,我会声明编码逻辑错误 应该在遇到它们时会引起恐慌。当然,此示例不是生产代码,处理错误情况取决于示例的用户和该应用程序的上下文。
    • 恕我直言,是的。如果可以的话,你应该避免所有这些。就我个人而言,我只有在确定这不会恐慌时才使用它们(即 FromPrimitive 常量)。如果我需要恐慌,那么它应该发生在main。在库中,您应该返回 ResultOption,或者如果不是致命的,则使用 log crate。
    • @Hauth关于错误的所有上下文。 panicexpect 各有所用。
    • 我希望有一个fn read_as_string() -> Result<String> 用于当我们还没有缓冲区时。在许多地方会更符合人体工程学。
    猜你喜欢
    • 2016-02-20
    • 2015-04-03
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2016-07-15
    • 2022-11-25
    相关资源
    最近更新 更多