Enum option parsing must be infallible? #5303
-
I'm trying to use an enum as a clap argument. use clap::Parser;
#[derive(Debug, Parser)]
#[command(version)]
pub struct Args {
#[clap(long, default_value_t)]
pub unified: Unified,
}
#[derive(Copy, Clone, Debug)]
pub enum Unified {
Num(u64),
Infinite,
}
impl std::fmt::Display for Unified {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Num(x) => write!(f, "{x}"),
Self::Infinite => write!(f, "infinite"),
}
}
}
impl Default for Unified {
fn default() -> Self {
Self::Num(5)
}
} As expected, this doesn't compile because there's no implementation to convert from string to
I don't know what any of that means, but it says it's missing a impl std::str::FromStr for Unified {
type Err = ();
fn from_str(_s: &str) -> Result<Self, Self::Err> {
todo!();
}
} Now we get the same error, except
We can try implementing impl<'a> From<&'a str> for Unified {
fn from(_s: &str) -> Self {
todo!();
}
} Now it works.
So my question is, does the enum parsing need to infalliable? This means the parsing needs to panic on invalid inputs, which isn't ideal. Are there any alternative ways to use enums with non-unit variants with clap? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Errors are supported but they must be compatible with clap's errors ( |
Beta Was this translation helpful? Give feedback.
Errors are supported but they must be compatible with clap's errors (
'static + Send + Sync
) and must be able to be shown to the user (Display
).