-
The // Approach 1, match-ing the Result
let arg: Option<Duration> = match value_t!(matches.value_of("arg"), humantime::Duration) {
Ok(t) => Ok(Some(t.into())),
Err(e) => {
match e.kind {
::clap::ErrorKind::ArgumentNotFound => Ok(None),
_ => Err(e),
}
}
}.unwrap_or_else(|e| e.exit());
// Approach 2, using map_or_else
let arg: Option<Duration> = value_t!(matches.value_of("arg"), humantime::Duration)
.map_or_else(|e| match e.kind {
::clap::ErrorKind::ArgumentNotFound => Ok(None),
_ => Err(e),
},
|v| Ok(Some(v.into())))
.unwrap_or_else(|e| e.exit()); Both of these feel cruftier than just re-implementing // Approach 3: don't use value_t! at all...
let arg: Option<Duration> = matches.value_of("arg")
.map(|v|
v.parse::<humantime::Duration>()
.map_err(|v| ::clap::Error::value_validation_auto(format!("The argument '{}' isn't a valid value", v)))
.unwrap_or_else(|e| e.exit())
.into()); Is there a different syntax that expresses this more clearly? What is the intended way for @CreepySkeleton tagging you since you implemented |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Well, you should probably handle parse failures before even coming here, so you generally don't need to check error kinds. |
Beta Was this translation helpful? Give feedback.
-
Sorry, took me a bit of time to understand what you are asking for. All the approaches you wrote are idiomatic. But I agree, things can be improved to handle the optional cases better. Can you please create an issue for this? |
Beta Was this translation helpful? Give feedback.
Sorry, took me a bit of time to understand what you are asking for. All the approaches you wrote are idiomatic. But I agree, things can be improved to handle the optional cases better. Can you please create an issue for this?