Skip to content

介绍

构建命令行应用参数解析库 clap

基础用法:定义参数

使用 derive 宏修饰 struct 定义命令行参数

rust
use clap::Parser;

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct CliArgs {
    /// server website root directory
    #[arg(short, long, default_value = ".")]
    dir: String,

    /// server listen port number
    #[arg(short, long, default_value_t = 80)]
    port: u16,
}

fn main() {
    let args = CliArgs::parse();

    // cargo run -- -d ./www -p 8080
    println!("got args:");
    println!("dir: {}", args.dir);
    println!("port: {}", args.port);
}
toml
[dependencies]
clap = { version = "4.5.20", features = ["derive"] }

Released under the MIT License.