Skip to content

Instantly share code, notes, and snippets.

@mmstick

mmstick/main.rs Secret

Created December 28, 2016 20:52
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 mmstick/797fbc1cf20c92f05d33a85c38e1ffb1 to your computer and use it in GitHub Desktop.
Save mmstick/797fbc1cf20c92f05d33a85c38e1ffb1 to your computer and use it in GitHub Desktop.
better example
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