BetterDebug

Derive Macro BetterDebug 

Source
#[derive(BetterDebug)]
{
    // Attributes available to this derive:
    #[better_debug]
}
Expand description

§Macro usage

Add the following to your Cargo.toml:

[dependencies]
better_debug = "1.0"

Then, add the following to your program:

use better_debug::BetterDebug;

#[derive(BetterDebug)]
struct Person {
    name: String,
    age: u8,
    secret: String,
}

The above code will implement fmt::Debug just like the standard library’s Debug macro. Essentially, you’ve made no changes.

§Cookbook recipes

§Ignore a custom struct member

This will completely prevent bar from being printed.

use better_debug::BetterDebug;

#[derive(BetterDebug)]
struct Foo {
    #[better_debug(ignore)]
    bar: String,
    baz: String,
}

§Rename a field

This will print bar as if it were new_name. Note that you can use just about anything, i.e. bar, Nice Bar!, etc.

use better_debug::BetterDebug;

#[derive(BetterDebug)]
struct Foo {
    #[better_debug(rename_to = "new_name")]
    bar: String,
    baz: String,
}

§Mark a field as a secret

This will set this field’s contents to <SECRET>, regardless of its actual contents.

use better_debug::BetterDebug;

#[derive(BetterDebug)]
struct Foo {
    #[better_debug(secret)]
    bar: String,
    baz: String,
}

§Use a custom formatter.

You can use a custom function to format the contents of a field.

This function must take a reference to the entire struct and return Some(dyn fmt::Debug) or None to use the default formatter. You can also return None to prevent the field from being printed.

Note that there’s no hard requirement in the return type of the function: you can return any Some(T) as long as T is printable, i.e. it implements fmt::Debug. The examples below use &'static str for convenience.

§Use a custom formatter with fallback

use better_debug::BetterDebug;

fn foo(foo: &Foo) -> Option<&'static str> {
    if foo.bar.len() < 5 {
        return Some("lorem ipsum");
    }
    None
}

#[derive(BetterDebug)]
struct Foo {
    #[better_debug(cust_formatter = "foo")]
    bar: String,
    baz: String,
}

§Use a custom formatter without fallback

use better_debug::BetterDebug;

fn foo(foo: &Foo) -> Option<&'static str> {
    if foo.bar != "lorem ipsum" {
        // If bar isn't equal to "lorem ipsum", then
        // don't print anything at all.
        return None;
    }
    Some("lorem ipsum is great")
}

#[derive(BetterDebug)]
struct Foo {
    #[better_debug(cust_formatter = "foo", cust_formatter_skip_if_none)]
    bar: String,
    baz: String,
}