0255-CLAP-增加子命令
环境
- Time 2022-12-02
- WSL-Ubuntu 22.04
- CLAP 4.0.29
前言
说明
参考:https://docs.rs/clap/latest/clap/index.html
目标
可以将命令进行分组,然后增加子命令。
Cargo.toml
[package]
edition = "2021"
name = "game"
version = "1.0.0"
[dependencies]
clap = {version = "4", features = ["cargo"]}
main.rs
use clap::{command, Arg, Command};
fn main() {
let matches = command!()
.subcommand(Command::new("set").arg(Arg::new("name").help("姓名")))
.get_matches();
match matches.subcommand() {
Some(("set", sub_matches)) => {
if let Some(param) = sub_matches.get_one::<String>("name") {
println!("set 的姓名是: {}", param);
}
}
_ => unreachable!(),
}
}
查看帮助
root@jiangbo12490:~/git/game# cargo run -- -h
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/game -h`
Usage: game [COMMAND]
Commands:
set
help Print this message or the help of the given subcommand(s)
Options:
-h, --help Print help information
-V, --version Print version information
使用
root@jiangbo12490:~/git/game# cargo run set 张三
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/game set '张三'`
set 的姓名是: 张三
总结
使用了子命令的功能。

浙公网安备 33010602011771号