Kim
Kim

Reputation: 197

How can I store an enum so I can retrieve it by only identifying the variant?

I have an enum like:

pub enum Component {
    Position { vector: [f64; 2] },
    RenderFn { render_fn: fn(Display, &mut Frame, Entity), },
}

I would like to store Components in a hashset/hashmap where they are identified only by their enum variant (Position or RenderFn).

There can be zero or one Position and zero or one RenderFn in the collection. I would like to be able to remove/retrieve it by passing an identifier/type (Position/RenderFn).

Is there any way to do this without any ugly hacks? Perhaps enums are not the way to go?

Upvotes: 1

Views: 450

Answers (1)

DK.
DK.

Reputation: 59005

It sounds like you want a structure, not a collection of enum variants.

struct Component {
    position: Option<[f64; 2]>,
    render_fn: Option<fn(Display, &mut Frame, Entity)>,
}

If this is likely to involve many kinds of components, and they mostly won't all be present, then maybe you want something like the typemap crate.

But to answer your question: no, a variant can't be separated from its associated values.

Upvotes: 2

Related Questions