[英]rust clap parse ipv4Addr
I want to use the clap derive API in order to parse an Ipv4Addr
.我想使用 clap derive API 来解析
Ipv4Addr
。
#![allow(unused)]
use clap; // 3.1.6
use clap::Parser;
use std::net::Ipv4Addr;
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
#[clap(short, long, parse(from_str))]
ip_dst: Ipv4Addr,
}
fn main() {
let args = Args::parse();
}
My attempt gives the following error even though Ipv4Addr seems to implement FromStr
which provides from_str
我的尝试给出了以下错误,即使 Ipv4Addr 似乎实现了提供
FromStr
的from_str
error[E0277]: the trait bound `Ipv4Addr: From<&str>` is not satisfied
--> src/main.rs:10:31
|
10 | #[clap(short, long, parse(from_str))]
| ^^^^^^^^ the trait `From<&str>` is not implemented for `Ipv4Addr`
|
= help: the following implementations were found:
<Ipv4Addr as From<[u8; 4]>>
<Ipv4Addr as From<u32>>
For more information about this error, try `rustc --explain E0277`.
My Questions are:我的问题是:
FromStr
used?FromStr
提供的方法呢? What you want is what is used by default (since Ipv4Addr
implements FromStr
), without specifiying any parse
option:你想要的是默认使用的(因为
Ipv4Addr
实现FromStr
),没有指定任何parse
选项:
use clap; // 3.1.6
use clap::Parser;
use std::net::Ipv4Addr;
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
#[clap(short, long)]
ip_dst: Ipv4Addr,
}
Otherwise, you need to use try_from_str
as per the example:否则,您需要按照示例使用
try_from_str
:
#![allow(unused)]
use clap; // 3.1.6
use clap::Parser;
use std::net::Ipv4Addr;
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
#[clap(short, long, parse(try_from_str))]
ip_dst: Ipv4Addr,
}
Update for Clap v4 Clap v4 更新
use clap::{arg, value_parser, Command}; // Clap v4
use std::net::Ipv4Addr;
fn main() {
let matches = Command::new("clap-test")
.arg(
arg!(--ip <VALUE>)
.default_value("127.0.0.1")
.value_parser(value_parser!(Ipv4Addr)),
)
.get_matches();
println!(
"IP {:?}",
matches.get_one::<Ipv4Addr>("ip").expect("required"),
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.