Writing Files in Rust

Here’s the translation of the Go code to Rust, with explanations in Markdown format suitable for Hugo:

Writing files in Rust follows similar patterns to the ones we saw earlier for reading.

use std::fs::File;
use std::io::{Write, BufWriter};

fn check(result: std::io::Result<()>) {
    if let Err(e) = result {
        panic!("{}", e);
    }
}

fn main() -> std::io::Result<()> {
    // To start, here's how to dump a string (or just bytes) into a file.
    let d1 = b"hello\nrust\n";
    std::fs::write("/tmp/dat1", d1)?;

    // For more granular writes, open a file for writing.
    let mut f = File::create("/tmp/dat2")?;

    // You can `write` byte slices as you'd expect.
    let d2 = [115, 111, 109, 101, 10];
    let n2 = f.write(&d2)?;
    println!("wrote {} bytes", n2);

    // A `write_all` is also available for writing strings.
    let n3 = f.write_all(b"writes\n")?;
    println!("wrote {} bytes", n3);

    // Issue a `flush` to ensure writes to stable storage.
    f.flush()?;

    // `BufWriter` provides buffered writers in addition
    // to the buffered readers we saw earlier.
    let mut w = BufWriter::new(f);
    let n4 = w.write(b"buffered\n")?;
    println!("wrote {} bytes", n4);

    // Use `flush` to ensure all buffered operations have
    // been applied to the underlying writer.
    w.flush()?;

    Ok(())
}

Try running the file-writing code.

$ cargo run
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
rust
$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin and stdout streams.