Error propagation

2021-08-25

~All ~Categories
use std::fs::File;
use std::io;
use std::fs;
use std::io::Read;

fn main() {
    let res = read_username_from_file();
    println!("{:?}", res);
}

fn read_username_from_file() -> Result<String, io::Error> {
    let f = File::open("hello.txt");

    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let mut s = String::new();

    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }
}
fn read_username_from_file_2() -> Result<String, io::Error> {
    let mut f = File::open("hello.txt")?; // ? shortcut for propagatin error
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    Ok(s)
}
fn read_username_from_file_3() -> Result<String, io::Error> {
    let mut s = String::new();
    File::open("hello.txt")?.read_to_string(&mut s)?; // chaining
    Ok(s)
}
fn read_username_from_file_4() -> Result<String, io::Error> {
    fs::read_to_string("hello.txt")
}