Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Write A String To A File In Rust

I searched for fifteen minutes for how to write a Rust `String` out to a file. Never did find it. Everything just shows how to write bytes. Probably that makes sense in ways that I don't understand but this works for what I'm trying to do.

This works though:

Code

use std::fs;

fn main() -> std::io::Result<()> {
    let text = String::from("alfa");
    fs::write("output.txt", text)?;
    Ok(())
}

And if you want it in a function:

Code

use std::fs;

fn main() {
    let text = String::from("bravo");
    match write_output(text) {
        Ok(()) => println!("Wrote the file"),
        Err(e) => println!("Error: {}", e),
    }
}



fn write_output(text: String) -> std::io::Result<()> {
    fs::write("output.txt", text)?;
    Ok(())
}