Print enum - enum name and variant

#![allow(unused)]
#[derive(Debug)]
enum E {
    V1,
}

#[derive(Debug)]
enum Message {
    Text(String),
    Number(i32),
}

fn main() {
    let v1 = E::V1;
    println!("{:?}", v1);

    let msg = Message::Number(5);
    println!("{:?}", msg);
}

(Playground)

Output:

V1
Number(5)

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 2.18s
     Running `target/debug/playground`

  1. I want to print enum v1 with enum name and variant - either as E::V1 or E(v1) - as long as both are printed.
    Do I have to implement fmt debug for E?
    impl std::fmt::Debug for E

There is no out of the box - print both (enum name and variant)?

  1. How about crate strum_macros or strum?
    How to print E::v1

  2. How about enum Message?
    Now I get:

  • Number(5)

Can I get:

  • Message::Number(5)

this is similar to asking about the variable type - Print the type of a variable - Hackertouch.com.

A better example why I think it would be helpful to display both:

#![allow(unused)]
#[derive(Debug)]
enum E {
    V1,
    V2,
}
#[derive(Debug)]
enum F {
    V1,
    V2,
}

fn main() {
    let e = E::V1;
    println!("{:?}", e); // I want  E::V1

    let f = F::V1;
    println!("{:?}", f); // I want  F::V1
}

A lazy solution would be to just prepend type_name::<Self>() to the derived Debug representation.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.