Enum with extra properties?

New to Rust here.
How can you express a list of constants with extra properties in Rust?
Something like an enum with extra (non-primitive) properties?

pub enum ItemProps {
	Brand = PropType.String,
	Model = PropType.String,
	Inventory = PropType.Integer,
	OrderableFrom = PropType.DateTime
}

Is there a way to accomplish something like this in Rust?

There’s two ways to do this kind of thing. Enum variants can directly contain additional data:

pub enum ItemProps {
    Brand(String),
    Model(String),
    Inventory(i32),
    OrderableFrom(DateTime)
}

fn example() {
    let v:Vec<ItemProps> = vec![
        Brand(String::from("Acme, Inc")), 
        Inventory(32)
    ];
}

If, instead, these are properties of the enum variants themselves, you can define a method like you would for a struct:

pub enum ItemProps {
    Brand,
    Model,
    Inventory,
    OrderableFrom
}

impl ItemProps {
    fn prop_type(&self)->PropType {
        use Self::*;
        use PropType::*;
        match self {
            &Brand => String,
            &Model => String,
            &Inventory => Integer,
            &OrderableFrom => DateTime
        }
    }
}

fn example() {
    assert_eq!(ItemProps::Model.prop_type(), PropType::String);
}
1 Like