I am trying to read a file and return it as a UTF-8 std:string:String it seems like content is a Result<collections::string::String, collections::vec::Vec<u8>> if i understand an error message i got from trying 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)
}
Check the functions provided by the io::Reader trait: https://doc.rust-lang.org/std/io/trait.Read.html
read_to_end() returns IoResult<Vec<u8>>, read_to_string() returns IoResult<String>.
IoResult<String> is just a handy way to write Result<String, IoError>: https://doc.rust-lang.org/std/io/type.Result.html
You can extract Strings from a Result either using unwrap():
let content = file.read_to_end();
content.unwrap()
or by handling the error yourself:
let content = file.read_to_end();
match content {
Ok(s) => s,
Err(why) => panic!("{}", why)
}
See also: http://doc.rust-lang.org/std/result/enum.Result.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With