How to generate a vec of enum options in Rust

Viewed 1163

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)

1 Answers

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"] }
Related