How to write to a file

Write to a file in Rust using std::fs::write for simple overwrites or File for advanced control.

Use std::fs::write to create a file or overwrite its contents with a string in one call.

use std::fs;

fn main() -> std::io::Result<()> {
    fs::write("hello.txt", "Hello, world!")?;
    Ok(())
}

For more control, like appending or writing in chunks, use File and BufWriter from std::fs and std::io.