ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

0261-CLAP-使用注解

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 -- -hFinished dev [unoptimized + debuginfo] target(s) in 0.01sRunning `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 -- -VFinished dev [unoptimized + debuginfo] target(s) in 0.01sRunning `target/debug/game -V`
game 1.0.0

使用

root@jiangbo12490:~/git/game# cargo run -- -n 张三Finished dev [unoptimized + debuginfo] target(s) in 0.01sRunning `target/debug/game -n '张三'`
姓名是:张三

总结

使用注解来解析命令行的参数。

附录

返回列表