Why debug print does not formatted an enum as expected?

Viewed 487

I need to print as debug a value from enum and format it. Then, I wrote this code like this:

#[derive(Debug)]
enum MyEnum {
    AB,
}

fn main() {
    let value = MyEnum::AB;
    println!("[{: <3?}]", value);
}

But, the result is [AB] while I expected that the result is [AB ]. Why? How to add paddings in a debug print?

1 Answers

This is not the behavior implemented when deriving Debug for an enum as you can see with:

#[derive(Debug)]
enum MyEnum {
    AB(i32),
}

fn main() {
    let value = MyEnum::AB(42);
    println!("[{:<3?}]", value);
}

Output:

[AB(42 )]

I think you need to implement Debug yourself:

enum MyEnum {
    AB,
}

use std::fmt;

impl fmt::Debug for MyEnum {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            MyEnum::AB => f.pad("AB"),
        }
    }
}

fn main() {
    let value = MyEnum::AB;
    println!("[{:<3?}]", value);
}

Output:

[AB ]
Related