Iterate a slice of enum variants

I have an enum like

pub enum StackValue {
    Value(f64),
    Values(Vec<f64>)
}

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 ?

Thanks

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!(),
}).collect();
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,
}).collect();
1 Like