Created
December 28, 2015 00:59
-
-
Save detro/0e279019e18ceeee4515 to your computer and use it in GitHub Desktop.
Rust very lean way to parse CLI params AND handle error cases
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
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