我遵循了 L. Riemer 的建议,似乎FromStr
只执行以下操作就足够了:
use structopt::StructOpt;
#[derive(Debug, PartialEq)]
struct Foo(Vec<String>);
impl std::str::FromStr for Foo {
type Err = Box<dyn std::error::Error>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Foo(s.split(",").map(|x| x.trim().to_owned()).collect()))
}
}
#[derive(StructOpt)]
pub struct Cli {
#[structopt(long, default_value = "foo, bar")]
foo: Foo,
}
fn main() {
let cli = Cli::from_iter(Vec::<String>::new());
assert_eq!(cli.foo, Foo(vec!["foo".into(), "bar".into()]));
let cli = Cli::from_iter(vec!["", "--foo", "foo"]);
assert_eq!(cli.foo, Foo(vec!["foo".into()]));
let cli = Cli::from_iter(vec!["", "--foo", "foo,bar,baz"]);
assert_eq!(cli.foo, Foo(vec!["foo".into(), "bar".into(), "baz".into()]));
}