Skip to content

How to refine parsing of associated value in enum variant? #32

Answered by frozenlib
fritzrehde asked this question in Q&A
Discussion options

You must be logged in to vote

By attaching #[from_str(new = ...)] to the variant as shown below, you can check the value and cause the parsing to fail.

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(…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by fritzrehde
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants