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:
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:
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(())
}
-- end of line --