인자 파싱
match를 사용하여 간단한 인자들을 파싱할 수 있습니다:
use std::env;
fn increase(number: i32) {
println!("{}", number + 1);
}
fn decrease(number: i32) {
println!("{}", number - 1);
}
fn help() {
println!("사용법:
match_args <string>
주어진 문자열이 정답인지 확인합니다.
match_args {{increase|decrease}} <integer>
주어진 정수를 1만큼 증가시키거나 감소시킵니다.");
}
fn main() {
let args: Vec<String> = env::args().collect();
match args.len() {
// 전달된 인자가 없음
1 => {
println!("제 이름은 'match_args'입니다. 인자를 전달해 보세요!");
},
// 한 개의 인자가 전달됨
2 => {
match args[1].parse() {
Ok(42) => println!("정답입니다!"),
_ => println!("정답이 아닙니다."),
}
},
// 하나의 명령어와 하나의 인자가 전달됨
3 => {
let cmd = &args[1];
let num = &args[2];
// 숫자를 파싱합니다
let number: i32 = match num.parse() {
Ok(n) => {
n
},
Err(_) => {
eprintln!("에러: 두 번째 인자가 정수가 아닙니다");
help();
return;
},
};
// 명령어를 파싱합니다
match &cmd[..] {
"increase" => increase(number),
"decrease" => decrease(number),
_ => {
eprintln!("에러: 유효하지 않은 명령어");
help();
},
}
},
// 그 외의 모든 경우
_ => {
// 도움말 메시지를 표시함
help();
}
}
}
프로그램 이름을 match_args.rs라고 짓고 rustc match_args.rs와 같이 컴파일했다면, 다음과 같이 실행할 수 있습니다:
$ ./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