2014-11-22 42 views
3

我想讀一個文件並返回它作爲一個UTF-8std:string:String好像contentResult<collections::string::String, collections::vec::Vec<u8>>如果我沒有理解錯誤信息,我從嘗試String::from_utf8(content)了。鏽創建file.read_to_end一個String()

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

回答

2

檢查由IO ::讀者特質所提供的功能: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>http://doc.rust-lang.org/std/io/type.IoResult.html

您可以使用展開()從結果中提取字符串:

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

+0

你會說'let s = String :: from_utf8(content).unwrap();'是在我返回之前將內容轉換爲'String'的好方法嗎?我的意思是使用的資源。 – Victory 2014-11-23 21:54:50

相關問題