问题描述
我来自 Java 背景,我可能有类似 enum Direction { NORTH, SOUTH, EAST, WEST}
的东西,我可以用增强的 for 循环依次对每个值做一些事情喜欢:
I come from a Java background and I might have something like enum Direction { NORTH, SOUTH, EAST, WEST}
and I could do something with each of the values in turn with the enhanced for loop like:
for(Direction dir : Direction.values()) {
//do something with dir
}
我想对 Rust 枚举做类似的事情.
I would like to do a similar thing with Rust enums.
推荐答案
不,没有.我认为这是因为 Rust 中的枚举比 Java 中的强大得多——它们实际上是成熟的代数数据类型.例如,您希望如何迭代此枚举的值:
No, there is none. I think that is because enums in Rust are much more powerful than in Java - they are in fact full-fledged algebraic data types. For example, how would you expect to iterate over values of this enum:
enum Option<T> {
None,
Some(T)
}
?
它的第二个成员 Some
不是静态常量 - 您可以使用它来创建 Option
的值:
Its second member, Some
, is not a static constant - you use it to create values of Option<T>
:
let x = Some(1);
let y = Some("abc");
所以没有理智的方法可以迭代任何枚举的值.
So there is no sane way you can iterate over values of any enum.
当然,我认为,可以在编译器中添加对 static 枚举(即只有静态项的枚举)的特殊支持,因此它会生成一些返回值的函数枚举或带有它们的静态向量,但我相信编译器中额外的复杂性是不值得的.
Of course, I think, it would be possible to add special support for static enums (i.e. enums with only static items) into the compiler, so it would generate some function which return values of the enum or a static vector with them, but I believe that additional complexity in the compiler is just not worth it.
如果你真的想要这个功能,你可以写一个自定义的语法扩展(见this 问题).这个扩展应该接收一个标识符列表,并以这些标识符作为内容输出一个枚举和一个静态常量向量.常规宏在某种程度上也可以工作,但据我所知,您不能两次转录具有多重性的宏参数,因此您必须手动编写两次枚举元素,这很不方便.
If you really want this functionality, you could write a custom syntax extension (see this issue). This extension should receive a list of identifiers and output an enum and a static constant vector with these identifiers as a content. A regular macro would also work to some extent, but as far as I remember you cannot transcript macro arguments with multiplicity twice, so you'll have to write enum elements twice manually, which is not convenient.
这个问题也可能引起一些人的兴趣:#5417
Also this issue may be of some interest: #5417
当然,您始终可以编写代码,手动返回枚举元素列表.
And of course you can always write code which returns a list of enum elements by hand.
这篇关于在 Rust 中,有没有办法遍历枚举的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!