Introduction
In this lab, we have an example of argument parsing using pattern matching in Rust. The program takes command-line arguments and performs different operations based on the number and type of arguments passed. If no arguments are passed, it prints a message. If a single argument is passed and it can be parsed as the integer 42, it prints "This is the answer!". If a command and an integer argument are passed, it performs either an increase or decrease operation on the integer. If any other number of arguments are passed, it shows a help message explaining the correct usage of the program.
Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use
main.rs, compile and run it withrustc main.rs && ./main.
Argument parsing
Matching can be used to parse simple arguments:
use std::env;
fn increase(number: i32) {
println!("{}", number + 1);
}
fn decrease(number: i32) {
println!("{}", number - 1);
}
fn help() {
println!("usage:
match_args <string>
Check whether given string is the answer.
match_args {{increase|decrease}} <integer>
Increase or decrease given integer by one.");
}
fn main() {
let args: Vec<String> = env::args().collect();
match args.len() {
// no arguments passed
1 => {
println!("My name is 'match_args'. Try passing some arguments!");
},
// one argument passed
2 => {
match args[1].parse() {
Ok(42) => println!("This is the answer!"),
_ => println!("This is not the answer."),
}
},
// one command and one argument passed
3 => {
let cmd = &args[1];
let num = &args[2];
// parse the number
let number: i32 = match num.parse() {
Ok(n) => {
n
},
Err(_) => {
eprintln!("error: second argument not an integer");
help();
return;
},
};
// parse the command
match &cmd[..] {
"increase" => increase(number),
"decrease" => decrease(number),
_ => {
eprintln!("error: invalid command");
help();
},
}
},
// all the other cases
_ => {
// show a help message
help();
}
}
}
$ ./match_args Rust
This is not the answer.
$ ./match_args 42
This is the answer!
$ ./match_args do something
error: second argument not an integer
usage:
match_args <string>
Check whether given string is the answer.
match_args {increase|decrease} <integer>
Increase or decrease given integer by one.
$ ./match_args do 42
error: invalid command
usage:
match_args <string>
Check whether given string is the answer.
match_args {increase|decrease} <integer>
Increase or decrease given integer by one.
$ ./match_args increase 42
43
Summary
Congratulations! You have completed the Argument Parsing lab. You can practice more labs in LabEx to improve your skills.