簡體   English   中英

rust從file.read_to_end()創建一個String

[英]rust create a String from file.read_to_end()

我正在嘗試讀取一個文件並將其作為UTF-8 std:string:String看起來contentResult<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)
}

檢查io :: Reader特性提供的功能: http//doc.rust-lang.org/std/io/trait.Reader.html

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

IoResult<String>只是編寫Result<String, IoError>一種方便方法: httpResult<String, IoError>

您可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM