Last active
May 9, 2019 01:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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