Skip to content

Instantly share code, notes, and snippets.

@detro
Created December 28, 2015 00:59
Show Gist options
  • Save detro/0e279019e18ceeee4515 to your computer and use it in GitHub Desktop.
Save detro/0e279019e18ceeee4515 to your computer and use it in GitHub Desktop.
Rust very lean way to parse CLI params AND handle error cases
fn main() {
// This might seem like a lot of lines for just catching the 2nd argument,
// parse the string to int and store it in a variable, but what this also covers is
// the absence of such value (first error case) or the non-parsability of the argument (second error case).
//
// I'm liking this stuff so far.
let n = match env::args().skip(1).next() {
Some(x) => match x.parse::<usize>() {
Ok(y) => y,
Err(_) => DEFAULT_N
},
None => DEFAULT_N
};
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment