Derive Macro racros::AutoDebug

source ·
#[derive(AutoDebug)]
{
    // Attributes available to this derive:
    #[debug_style]
    #[debug_format]
    #[debug_name]
    #[debug_value]
    #[debug_ignore]
    #[debug_debug]
    #[debug_display]
}
Expand description

Generate debug trait implementation for structs and enums with control.

§Usage

  • #[derive(AutoDebug)] makes a struct style debug implementation.

§Struct Attributes

  • #[debug_style = tuple] makes a tuple style debug implementation. Default is struct style.
  • #[debug_format = display] uses Display trait on fields. Default is debug format.

§Struct Field Attributes

  • #[debug_name = "foo"] override field name with “foo”, if in struct debug_style.
  • #[debug_value = "foo"] override field value with “foo”.
  • #[debug_ignore] will ignore this field in the output.
  • #[debug_debug] will use Debug trait implementation for this field in output.
  • #[debug_display] will use Display trait implementation for this field in output.

§Enum Variant Attributes

  • #[debug_ignore]
  • #[debug_debug]
  • #[debug_display]

§Example

use racros::AutoDebug;
use std::fmt::{format, Formatter};

struct MyType {}

impl std::fmt::Debug for MyType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str("debug MyType")
    }
}

impl std::fmt::Display for MyType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str("display MyType")
    }
}

// Struct

#[derive(AutoDebug)]
struct Foo1 {
    #[debug_name = "my_foo1"]
    foo1: MyType,
    #[debug_ignore]
    foo2: MyType,
    #[debug_display]
    foo3: MyType,
    #[debug_value = "foo4, MyType"]
    foo4: MyType,
}

#[derive(AutoDebug)]
#[debug_format = "display"]
#[debug_style = "tuple"]
struct Foo2 {
    #[debug_debug]
    foo1: MyType,
    foo2: MyType,
}

let foo1 = Foo1 {
    foo1: MyType {},
    foo2: MyType {},
    foo3: MyType {},
    foo4: MyType {},
};

assert_eq!(
    format(format_args!("{:#?}", foo1)),
    r#"Foo1 {
    my_foo1: debug MyType,
    foo3: display MyType,
    foo4: "foo4, MyType",
}"#
 );

let foo2 = Foo2 {
    foo1: MyType {},
    foo2: MyType {},
};

assert_eq!(
    format(format_args!("{:#?}", foo2)),
    r#"Foo2(
    debug MyType,
    display MyType,
)"#
    );

// Enum

#[derive(AutoDebug)]
enum Foo3 {
    Foo1,
    Foo2((i32, u32)),
    Foo3(Foo2),
    Foo4 { a: i32, b: u32 },
}

let foo33 = Foo3::Foo3(Foo2 {
    foo1: MyType {},
    foo2: MyType {},
});
assert_eq!(
    format(format_args!("{:#?}", foo33)),
    r#"Foo3(
    Foo2(
        debug MyType,
        display MyType,
    ),
)"#
);

let foo34 = Foo3::Foo4 { a: -100, b: 200 };
assert_eq!(
    format(format_args!("{:#?}", foo34)),
    r#"{
    a: -100,
    b: 200,
}"#
);