0
pub enum MyEnum{
    Int(i32),
    Float(f32)
}
fn convert(my_vec:Vec<i32>) -> Vec<MyEnum>
{
    //??
}

I need to convert a vector of ints to a vector of enum type Int.

crispy
  • 3
  • 4
  • Note that you likely don't want to take `&Vec` - see https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-to-a-string-string-vec-vec-o. – Cerberus Aug 15 '22 at 12:35
  • Note that the return type of `convert` is `Vec` not `Vec`. `Int` isn't a type, it's a variant. – isaactfa Aug 15 '22 at 12:42

1 Answers1

5

A simple map() + collect() will do:

my_vec.iter().map(|v| MyEnum::Int(*v)).collect::<Vec<_>>()
// Or
my_vec.iter().copied().map(MyEnum::Int).collect::<Vec<_>>()
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77