使用拍手的#[derive(parser)],我如何接受std :: time ::持续时间?
我想在命令行上接受 std :: Time ::持续时间
。我正在使用 clap
和##[derive(parser)]
生成参数解析器。有什么办法可以直接接受输入,而不是接受数字并在以后进行转换?
这样的事情:
#[derive(Debug, Parser)]
pub struct Config {
#[clap( ??? )]
interval: std::time::Duration,
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
clap 4
文档的紧凑型版本:
https://docs.rs/clap/latest/clap/macro.value_parser.html
Compact version for Clap 4
Docs for value_parser:
https://docs.rs/clap/latest/clap/builder/struct.ValueParser.html#method.new
https://docs.rs/clap/latest/clap/macro.value_parser.html
我认为没有一种方法可以区分
u8
或与std :: Time ::持续时间
在命令行本身上的其他方法。 那么您应该能够执行此类操作。也就是说,如果您实现 for distation :但是,您绝对更容易采用
u8
, >并在main()
或类似过程中进行转换。I don't think there's a way to differentiate a
u8
or whatever from astd::time::Duration
on the command line itself. That said, you should be able to do something like this if you implementFromStr
forDuration
:But it definitely seems easier to take something like a
u8
and do a conversion inmain()
or similar.拍手3.0:
要进行自定义解析,您应该使用
#[clap(parse(try_from_str = ...))]
并定义一个自定义函数以解析参数。这是一个例子:拍手4.0:
几乎与上面相同;辅助功能可以保持不变,但是属性语法已经改变:
通过humanantime进行解析,
解析非常有限(我不知道您期望持续时间是什么格式),但它显示了您如何做的它。
如果您想在持续时间的争论中灵活地提高论点,请考虑使用“ 5S” 或
“ 3小时”
之类的单元标签。您可以使用其辅助功能将其解析为std :: Time ::持续时间
(使用CLAP 4语法):或者您可以使用
humantime ::持续时间
没有特殊属性,因为它在str 上实现了。
Clap 3.0:
To do custom parsing, you should use
#[clap(parse(try_from_str = ...))]
and define a custom function to parsing the argument. Here's an example:Clap 4.0:
Almost same as above; the helper function can stay the same, but the attribute syntax has changed:
Parsing with humantime
This parsing is pretty limited (I don't know what format you'd expect the duration to be in), but it shows how you'd do it.
If you want to be flexible with your duration arguments, consider using a crate like humantime, which lets you provide durations with unit labels like
"5s"
or"3 hours"
. You can either use their helper function to parse into astd::time::Duration
(using clap 4 syntax):Or you can use
humantime::Duration
without special attributes since it implementsFromStr
.