参数解析

可以用模式匹配来解析简单的参数:

  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. // 没有传入参数
  19. 1 => {
  20. println!("My name is 'match_args'. Try passing some arguments!");
  21. },
  22. // 一个传入参数
  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. // 传入一条命令和一个参数
  30. 3 => {
  31. let cmd = &args[1];
  32. let num = &args[2];
  33. // 解析数字
  34. let number: i32 = match num.parse() {
  35. Ok(n) => {
  36. n
  37. },
  38. Err(_) => {
  39. println!("error: second argument not an integer");
  40. help();
  41. return;
  42. },
  43. };
  44. // 解析命令
  45. match &cmd[..] {
  46. "increase" => increase(number),
  47. "decrease" => decrease(number),
  48. _ => {
  49. println!("error: invalid command");
  50. help();
  51. },
  52. }
  53. },
  54. // 所有其他情况
  55. _ => {
  56. // 显示帮助信息
  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