0261-CLAP-使用注解
环境
- Time 2022-12-03
- 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 = ["derive"]}
main.rs
use clap::Parser;
/// 命令行参数
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Args {
/// 姓名
#[arg(short, long)]
name: String,
}
fn main() {
let args = Args::parse();
println!("姓名是:{}", args.name);
}
查看帮助
root@jiangbo12490:~/git/game# cargo run -- -h
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/game -h`
命令行参数
Usage: game --name <NAME>
Options:
-n, --name <NAME> 姓名
-h, --help Print help information
-V, --version Print version information
查看版本
root@jiangbo12490:~/git/game# cargo run -- -V
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/game -V`
game 1.0.0
使用
root@jiangbo12490:~/git/game# cargo run -- -n 张三
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/game -n '张三'`
姓名是:张三
总结
使用注解来解析命令行的参数。

浙公网安备 33010602011771号