How to refine parsing of associated value in enum variant? #32
-
I'm using #[derive(Hash, Eq, PartialEq, From, Clone, Debug, Display, FromStr)]
#[display(style = "lowercase")]
enum KeyCode {
// ... other variants ...
#[display("f{0}")]
F(u8),
// ... other variants ...
} How can I do this? It would be cool if I could just pass a lambda/closure to the macro that returns true or false and that would be evaluated when parsing, and if it returns false then the parsing would fail. Thanks for the help! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
By attaching use parse_display::{Display, FromStr};
#[derive(Hash, Eq, PartialEq, Clone, Debug, Display, FromStr)]
#[display(style = "lowercase")]
enum KeyCode {
// ... other variants ...
#[display("f{0}")]
#[from_str(new = Self::new_f(_0))]
F(u8),
// ... other variants ...
}
impl KeyCode {
fn new_f(value: u8) -> Option<Self> {
if (1..=12).contains(&value) {
Some(KeyCode::F(value))
} else {
None
}
}
}
fn main() {
use std::str::FromStr;
println!("{:?}", KeyCode::from_str("f13")); // Err(ParseError("parse failed."))
println!("{:?}", KeyCode::from_str("f12")); // Ok(F(12))
} |
Beta Was this translation helpful? Give feedback.
By attaching
#[from_str(new = ...)]
to the variant as shown below, you can check the value and cause the parsing to fail.