Skip to content

Instantly share code, notes, and snippets.

@sts10
Last active May 9, 2019 01:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sts10/555205fc79aacbb388b666956ba34c5e to your computer and use it in GitHub Desktop.
Save sts10/555205fc79aacbb388b666956ba34c5e to your computer and use it in GitHub Desktop.
Rust script defining function that can write either to Terminal or a file
use std::fs::File;
use std::io::{self, Write};
#[derive(Debug)]
pub enum Destination<'a> {
Terminal,
File(&'a std::fs::File),
}
fn main() {
print_report(Destination::Terminal).expect("Error printing report to terminal");
let file = File::create("report.txt").expect("Error creating file");
print_report(Destination::File(&file)).expect("Error printing report to file");
}
fn print_report(dest: Destination) -> std::io::Result<()> {
write_to(&dest, "Report Title".to_string())?;
write_to(&dest, "Line 2 of report".to_string())?;
Ok(())
}
fn write_to(dest: &Destination, output: String) -> std::io::Result<()> {
match dest {
Destination::File(mut f) => {
writeln!(f, "{}", &output)?;
Ok(())
}
Destination::Terminal => {
// println!("{}", &output);
let stdout = io::stdout(); // get the global stdout entity
let mut handle = stdout.lock(); // acquire a lock on it
writeln!(handle, "{}", output)?; // add `?` if you care about errors here
Ok(())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment