Optimizing String Enum that should be stored into a vector

I have the following Enum with String values and want to prevent a hard coded into_vec() function. What should I do to optimize it?

pub enum Topics {
    FAVORITE_ANIMAL,
    LEISURE_I,
    LEISURE_II,
    LEISURE_III,
    ONLINE_GAMING_FAN,
    DIY,
    PLASTIC,
    NUTRITION
}

impl Topics {
    pub fn as_str(&self) -> &'static str {
        match self {
            Topics::FAVORITE_ANIMAL => "Favorite Animal",
            Topics::LEISURE_I => "Leisure I",
            Topics::LEISURE_II => "Leisure II",
            Topics::LEISURE_III => "Leisure III",
            Topics::ONLINE_GAMING_FAN => "Online Gaming Fan",
            Topics::DIY => "Do it yourself",
            Topics::PLASTIC => "Plastic",
            Topics::NUTRITION => "Nutrition"
        }
    }

    // How can I optimize this function to prevent the hardcoded variant
    pub fn into_vec(&self) -> Vec<&'static str> {
        let mut vec = Vec::new();
        let fav_an = Topics::FAVORITE_ANIMAL.as_str();
        vec.push(fav_an);
        let leisure_1 = Topics::LEISURE_I.as_str();
        vec.push(leisure_1);

        vec
    }
}

Sounds to me like you want to derive strum::VariantNames on your enum.

/*
[dependencies]
strum = { version = "0.26", features = ["derive"] }
*/
#![allow(non_camel_case_types)]

use strum::{VariantNames};

#[derive(VariantNames)]
pub enum Topics {
    #[strum(to_string = "Favorite Animal")]
    FAVORITE_ANIMAL,
    #[strum(to_string = "Leisure I")]
    LEISURE_I,
    #[strum(to_string = "Leisure II")]
    LEISURE_II,
    #[strum(to_string = "Leisure III")]
    LEISURE_III,
    #[strum(to_string = "Online Gaming Fan")]
    ONLINE_GAMING_FAN,
    #[strum(to_string = "Do it yourself")]
    DIY,
    #[strum(to_string = "Plastic")]
    PLASTIC,
    #[strum(to_string = "Nutrition")]
    NUTRITION
}

fn main() {
    println!("{:?}", Topics::VARIANTS);
}

Rustexplorer.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.