Rust creates a line from file.read_to_end ()

I am trying to read a file and return it as UTF-8

std:string:String

it looks like it content

is Result<collections::string::String, collections::vec::Vec<u8>>

if I understand the 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)
}

      

+3


source to share


1 answer


Check out the functions provided by io :: Reader: http://doc.rust-lang.org/std/io/trait.Reader.html

read_to_end () returns IoResult<Vec<u8>>

, read_to_string () returns IoResult<String>

.

IoResult<String>

is just a convenient way to write Result<String, IoError>

: http://doc.rust-lang.org/std/io/type.IoResult.html

You can extract rows from the result either by using the reversal () function:



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

+2


source







All Articles