Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

rust - 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,
}

I can derive Debug and do

writer.write(format!("I am {:?}", Foo::Quux).as_bytes())

which will output e.g. I am Quux. That's fine, except that

  • I want to do this for user-facing output, so Debug isn't appropriate
  • It would be very helpful to get the enum as a string (rather than writing directly to a stream), because then I can incorporate its length into some wonky formatting calculations I want to do.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
    }
}

Then you can use to_string() to get a String representation:

let s: String = Foo::Quux.to_string();

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...