3

Is there a way to do the below by iterating over enum in Rust.

enum ProductCategory{
    Dairy,
    Daycare,
    BabyCare
}

fn main() {

    let product_categories = vec![ProductCategory::Dairy, ProductCategory::Daycare, ProductCategory::BabyCare];

}

This to send over an api what all the possible value a user can select for a particular field. (serde serialize will be added)

Asnim P Ansari
  • 1,932
  • 1
  • 18
  • 41

1 Answers1

1

A quick example using the strum crate.

let product_categories: Vec<_> = ProductCategory::iter().collect();

With this crate, you can iterate over the variants of enums, convert them to/from string representation, associate string metadata with variants, etc...

The complete example:

use strum::{IntoEnumIterator, EnumIter};

#[derive(Debug, EnumIter)]
enum ProductCategory {
    Dairy, Daycare, BabyCare,
}

fn main() {
    let product_categories = ProductCategory::iter().collect::<Vec<_>>();
    println!("{:?}", product_categories);
}

output:

[Dairy, Daycare, BabyCare]

Add to Cargo.toml:

[dependencies]
strum = { version = "0.21", features = ["derive"] }
Todd
  • 4,669
  • 1
  • 22
  • 30
  • how your answer different than https://stackoverflow.com/a/55056427/7076153 ? – Stargateur Jul 18 '21 at 10:30
  • It shows usage of `.collect()` in answer to the specific title of this post, "generate a vec of enum options". The other example just iterates over them @Stargateur – Todd Jul 18 '21 at 10:32