Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Write A String To A File In Rust

I searched for fifteen minutes for how to write a Rust [TODO: Code shorthand span ] 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 :

rust
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 :

rust
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(())
}