-
-
Save mmstick/797fbc1cf20c92f05d33a85c38e1ffb1 to your computer and use it in GitHub Desktop.
better example
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::env; | |
use std::io; | |
use std::fs::File; | |
use std::process::exit; | |
enum ProgramErr { | |
UnableToOpenFile(io::Error) | |
} | |
fn main() { | |
let path = env::args().nth(1).unwrap_or("/usr/share/dict/words".to_owned()); | |
if let Err(why) = open_input(&path) { | |
match why { | |
ProgramErr::UnableToOpenFile(reason) => { | |
let _ = writeln!(io::stderr(), "program: unable to open {}: {}", path, reason); | |
} | |
} | |
exit(1); | |
} | |
} | |
fn open_input(path: &str) -> Result<(), ProgramErr> { | |
if path == "-" { | |
let stdout = io::stdout(); | |
do_something_with(stdout.lock()) | |
} else { | |
do_something_with(File::open(path).map_err(ProgramErr::UnableToOpenFile)?); | |
}; | |
Ok(()) | |
} | |
fn do_something_with<I: Read>(input_source: I) { | |
// do something | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment