Reputation: 5890
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)
}
Upvotes: 3
Views: 6869
Reputation: 1637
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
Upvotes: 2