Iterate a slice of enum variants

I have an enum like

pub enum StackValue {

If I have a slice of these enums is it possible to iterate through that slice
and collect a vector or Value (Assuming I know the stack only contains StackValue::Value)

ie something like this

let params : Vec = stack_values_params.iter().map(|i: StackValue| i.Value).collect();

or is loop through and performing a match the only way ?


You can't just assume the enum value is a particular variant, you need to check for this in your code. For example:

stack_values_params.iter().map(|v| match v {
    StackValue::Value(v) => v,
    StackValue::Values(_) => panic!(),
1 Like

If you want to skip non-matching items rather than panic, you can use filter_map:

stack_values_params.iter().filter_map(|v| match v {
    StackValue::Value(v) => Some(v),
    _ => None,
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.