How to get value of enum in Vector of enum's?

I want to get value of a member of vector that becames from Token's

enum Token {
    Int { val: u32 },
    Add,
    Multiply,
    Minus,
    Divide
}

fn main() {
    let mut list: Vec<Token> = Vec::new();
    list.push(Token::Int { val: 10 });
    if matches!(list[0], Token::Int { val }) {
        println!("{}", list[0].val);
    }
}

Error is at list[0].val

    let filter = list.iter().filter_map(|t| {
        if let Token::Int { val } = t {
            Some(val)
        } else {
            None
        }
    });
    for r in filter {
        dbg!(r);
    }

playground

There are some macros that make this specific use case more ergonomic, such as the enum_extract crate which lets you simply write

list.iter().filter_map(|t| extract!(Token::Int { val }, t))
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.