简体   繁体   English

如何存储枚举,以便仅通过识别变体就可以检索它?

[英]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 Component s in a hashset/hashmap where they are identified only by their enum variant ( Position or RenderFn ). 我想将Component存储在哈希集/哈希图中,其中仅通过其枚举变量( PositionRenderFn )来标识它们。

There can be zero or one Position and zero or one RenderFn in the collection. 集合中可以有零个或一个Position以及零个或一个RenderFn I would like to be able to remove/retrieve it by passing an identifier/type ( Position / RenderFn ). 我希望能够通过传递一个标识符/类型( Position / RenderFn )来删除/检索它。

Is there any way to do this without any ugly hacks? 有没有办法做到这一点而没有任何难看的骇客? Perhaps enums are not the way to go? 也许枚举不是要走的路?

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. 如果这是可能的多种成分参与,他们大多不会悉数到场,那么也许你想要的东西,如typemap箱子。

But to answer your question: no, a variant can't be separated from its associated values. 但是要回答您的问题:不,一个变体不能与其关联的值分开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何动态确定枚举的变体 - How can I dynamically determine the variant of an enum 当给定的枚举不是某种变体时,如何返回None? - How can I return None when a given enum is not a certain variant? 如何根据与变体中的类型匹配的泛型类型选择枚举变体? - How can I select an enum variant based on a generic type that matches a type inside the variant? 如何在将字段移动到新变体时更改枚举变体? - How can I change enum variant while moving the field to the new variant? 是否有一个宏可以用来期待枚举的变体并提取其数据? - Is there a macro I can use to expect a variant of an enum and extract its data? 在将值移入元组类型枚举变体后,如何轻松获取对值的引用? - How can I easily get a reference to a value after it has been moved into a tuple-type enum variant? 如何对枚举进行变异,然后返回对枚举变体的引用? - How do I mutate an enum and then return a reference to an enum variant? 如何在不包含枚举变量名称的情况下序列化枚举? - How do I serialize an enum without including the name of the enum variant? 我可以将元组结构枚举变量转换为常规元组,而不是解构和重新创建元组吗? - Can I cast a tuple struct enum variant into a regular tuple instead of destructuring and recreating the tuple? 如何传递枚举变量以匹配作为函数参数? - How do I pass an enum variant to match on as a function parameter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM