如何将枚举作为字符串获取? [英] How do I get an enum as a string?
问题描述
我有一个包含许多值的枚举,我想将其中一个值的名称写入流:
I have an enum with many values and I'd like to write the name of one of its values to a stream:
enum Foo {
Bar = 0x00,
Baz = 0x01,
Qux = 0x02,
// ...
Quux = 0xFF,
}
我可以导出Debug
并做
writer.write(format!("I am {:?}", Foo::Quux).as_bytes())
将输出例如我是库克斯
.没关系,除了
which will output e.g. I am Quux
. That's fine, except that
- 我想为面向用户的输出执行此操作,因此
Debug
不合适 - 将枚举作为字符串获取(而不是直接写入流)会非常有帮助,因为这样我就可以将其长度合并到我想做的一些不稳定的格式计算中.
推荐答案
可能最简单的方法是通过调用Debug
来实现Display
:
Probably the easiest way would be to implement Display
by calling into Debug
:
impl fmt::Display for Foo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
// or, alternatively:
// fmt::Debug::fmt(self, f)
}
}
然后你可以使用 to_string()
得到一个 String
表示:
Then you can use to_string()
to get a String
representation:
let s: String = Foo::Quux.to_string();
如果您有许多要打印的枚举,您可以编写一个简单的宏来为每个枚举生成上述 Display
的实现.
If you have many enums which you want to print, you can write a trivial macro to generate the above implementation of Display
for each of them.
不幸的是,在 Rust 中反射编程有点困难.例如,没有标准方法可以获取类 C 枚举的所有变体的列表.几乎总是你必须用自定义编写的宏来抽象样板(或者在 crates.io 上找到一些东西).如果有人编写 RFC 并被接受,这可能会在未来发生变化.
Unfortunately, in Rust reflective programming is somewhat difficult. There is no standard way, for example, to get a list of all variants of a C-like enum. Almost always you have to abstract the boilerplate with custom-written macros (or finding something on crates.io). Maybe this will change in future if someone would write an RFC and it would get accepted.
这篇关于如何将枚举作为字符串获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!