从文件.read_to_end()创建一个字符串的 Rust 方法

3

我正在尝试读取一个文件并将其作为UTF-8std:string:String返回,看起来content是一个Result<collections::string::String, collections::vec::Vec<u8>>,如果我理解了从尝试String::from_utf8(content)得到的错误消息。

fn get_index_body () -> String {
    let path = Path::new("../html/ws1.html");
    let display = path.display();
    let mut file = match File::open(&path) {
        Ok(f) => f,
        Err(err) => panic!("file error: {}", err)
    };

    let content = file.read_to_end();
    println!("{} {}", display, content);

    return String::new(); // how to turn into String (which is utf-8)
}
1个回答

2

请查看io::Reader trait提供的函数:https://doc.rust-lang.org/std/io/trait.Read.html

read_to_end()返回IoResult<Vec<u8>>,read_to_string()返回IoResult<String>

IoResult<String>只是一种方便的写法,用于表示Result<String, IoError>https://doc.rust-lang.org/std/io/type.Result.html

您可以使用unwrap()从结果中提取字符串:

let content = file.read_to_end();
content.unwrap()

或者通过自己处理错误:

let content = file.read_to_end();
match content {
    Ok(s) => s,
    Err(why) => panic!("{}", why)
}

另请参阅:http://doc.rust-lang.org/std/result/enum.Result.html


你认为 let s = String::from_utf8(content).unwrap(); 这种方式在将内容转换为 String 后返回它是一个好的选择吗?我指的是资源使用方面。 - Victory

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接