How to handle the error maybe caused by File.write_all?

My code like this:

pub fn write_string_into_file(file_path: String, file_content: String) -> Result<bool, io::Error> {
    let mut f = match File::create(file_path) {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let www = f.write_all(file_content.as_bytes());
    //How to handle the error maybe caused 
}

Thank you

Here is a new version:

pub fn write_string_into_file(file_path: String, file_content: String) -> Result<bool, io::Error> {
    let mut f = match File::create(file_path) {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    if let Err(e) = f.write_all(file_content.as_bytes()) {
        return Err(e);
    }
    Ok(true)
}

Is it perfect?

The ? (try) operator is a shorthand for this:

let mut f = File::create(file_path)?;
f.write_all(file_content.as_bytes())?;

and btw, there's std::fs::write(path, bytes) that does it all in one go.

1 Like