【开发总结】Rust的命令行库clap

偶然了解到Rust中有命令行处理的相关库clap,可以很方便的解决程序员需要编写命令行程序时的命令行输入参数问题。

在CSDN中找到了一篇文章进行学习,将一些感想记录如下:

首先该文章的运行环境是cargo,首先需要通过

复制代码
cargo new "项目名"

指令创建一个新的项目。

作者在第一段给出了一个官方文档中的例子,却并没有介绍程序功能和如何运行,查阅GPT后发现这段程序可以根据用户输入的名字和次数输出相应的打招呼内容。

运行指令为

复制代码
cargo run -- -n test -c 5

同时还支持完全的命令方式调用(这也是clap的默认提示,如果用户输入错误的话会以此形式提示)

复制代码
cargo run -- --name test --count 5

程序将会输出5次Hello test!

关注到上述例子中有一个为default_value_t的形参,通过测试发现,如果是系统默认的OsStr类型,也即字符串,可以通过default_value指定,否则会报错:

bash 复制代码
error[E0308]: mismatched types
 --> src/main.rs:8:42
  |
8 |     #[arg(short, long, default_value_t = "World")] // 设置 name 字段的默认值     ...
  |                                          ^^^^^^^- help: try using a conversion method: `.to_string()`
  |                                          |
  |                                          expected `String`, found `&str`
9 |     name: String,
  |           ------ expected due to this

需要把str转成String,但是在形参部分却不支持.to_string()转换方法,又无法在结构体内部定义变量,查阅GPT发现,可以使用default_value类型直接处理此种情况,因为此时需要传入的是字符串(下一部分将会看到为什么只有字符串才能如此处理)

如果将default_value_t = 1改为default_value = 1,将会报错如下:

bash 复制代码
error[E0277]: the trait bound `clap::builder::OsStr: From<{integer}>` is not satisfied
    --> src/main.rs:12:40
     |
12   |     #[arg(short, long, default_value = 1)]
     |                        -------------   ^ the trait `From<{integer}>` is not implemented for `clap::builder::OsStr`
     |                        |
     |                        required by a bound introduced by this call
     |
     = help: the following other types implement trait `From<T>`:
               <clap::builder::OsStr as From<Str>>
               <clap::builder::OsStr as From<&clap::builder::OsStr>>
               <clap::builder::OsStr as From<&Str>>
               <clap::builder::OsStr as From<&&'static std::ffi::OsStr>>
               <clap::builder::OsStr as From<&&'static str>>
               <clap::builder::OsStr as From<&'static std::ffi::OsStr>>
               <clap::builder::OsStr as From<&'static str>>
     = note: required for `{integer}` to implement `Into<clap::builder::OsStr>`
     = note: required for `{integer}` to implement `IntoResettable<clap::builder::OsStr>`

可以看到,default_value默认支持的是OsStr类型的,也即字符串,因此需要将其改为default_value = "1"才能通过编译。

最后一段例子3 自定义验证逻辑中有两个->接中文注释的部分,此部分为注释,应该以//开头。

最后一个例子是没有指令flag的short 和long name的,所以只能直接输入参数,无法通过--port 8080的方式调用。

相关推荐
mit6.8242 小时前
论容器化 | 分析Go和Rust做医疗的后端服务
docker·golang·rust
Source.Liu7 小时前
【unitrix】 4.21 类型级二进制数基本结构体(types.rs)
rust
SoniaChen337 小时前
Rust基础-part2-变量和可变类型
开发语言·后端·rust
寻月隐君8 小时前
Rust 错误处理终极指南:从 panic! 到 Result 的优雅之道
后端·rust·github
CHANG_THE_WORLD21 小时前
Rustup 安装加速:使用国内镜像源解决下载慢问题
rust·rustup
萧曵 丶1 天前
Rust 仿射类型(Affine Types)
rust·仿射类型
寻月隐君1 天前
Rust核心利器:枚举(Enum)与模式匹配(Match),告别空指针,写出优雅健壮的代码
后端·rust·github
小Lu的开源日常2 天前
在 Mac 上使用 iTerm2 和 Oh My Zsh 打造优雅终端
macos·iterm·命令行
泊浮目2 天前
生产级Rust代码品鉴(一)RisingWave一条SQL到运行的流程
大数据·后端·rust
得物技术2 天前
从Rust模块化探索到DLB 2.0实践|得物技术
rust