Argument parsing

Matching can be used to parse simple arguments:

  1. use std::env;
  2. fn increase(number: i32) {
  3. println!("{}", number + 1);
  4. }
  5. fn decrease(number: i32) {
  6. println!("{}", number - 1);
  7. }
  8. fn help() {
  9. println!("usage:
  10. match_args <string>
  11. Check whether given string is the answer.
  12. match_args {{increase|decrease}} <integer>
  13. Increase or decrease given integer by one.");
  14. }
  15. fn main() {
  16. let args: Vec<String> = env::args().collect();
  17. match args.len() {
  18. // no arguments passed
  19. 1 => {
  20. println!("My name is 'match_args'. Try passing some arguments!");
  21. },
  22. // one argument passed
  23. 2 => {
  24. match args[1].parse() {
  25. Ok(42) => println!("This is the answer!"),
  26. _ => println!("This is not the answer."),
  27. }
  28. },
  29. // one command and one argument passed
  30. 3 => {
  31. let cmd = &args[1];
  32. let num = &args[2];
  33. // parse the number
  34. let number: i32 = match num.parse() {
  35. Ok(n) => {
  36. n
  37. },
  38. Err(_) => {
  39. eprintln!("error: second argument not an integer");
  40. help();
  41. return;
  42. },
  43. };
  44. // parse the command
  45. match &cmd[..] {
  46. "increase" => increase(number),
  47. "decrease" => decrease(number),
  48. _ => {
  49. eprintln!("error: invalid command");
  50. help();
  51. },
  52. }
  53. },
  54. // all the other cases
  55. _ => {
  56. // show a help message
  57. help();
  58. }
  59. }
  60. }
  1. $ ./match_args Rust
  2. This is not the answer.
  3. $ ./match_args 42
  4. This is the answer!
  5. $ ./match_args do something
  6. error: second argument not an integer
  7. usage:
  8. match_args <string>
  9. Check whether given string is the answer.
  10. match_args {increase|decrease} <integer>
  11. Increase or decrease given integer by one.
  12. $ ./match_args do 42
  13. error: invalid command
  14. usage:
  15. match_args <string>
  16. Check whether given string is the answer.
  17. match_args {increase|decrease} <integer>
  18. Increase or decrease given integer by one.
  19. $ ./match_args increase 42
  20. 43