How to display constants as it's name for rust when debug

I have a field in my struct that may be a constant. for example:

struct Age(i32);
impl Age {
   const ZERO: Age = Age(0);
   const INVALID: Age = Age(-1);
   pub fn new(age: i32) -> Self {
      Self(age)
  }
}

struct Person {
   age: Age
}

let baby = Person {
  age: Age::ZERO
};
let tom = Person {
  age: Age::new(10)
}

While debugging I see that the age field of baby is 0. And tom's age is 10. Is there some way to format baby age field as Age::ZERO

old
impl fmt::Debug for Age {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Age")
            .field(
                "age",
                match &self.0 {
                    0 => &"ZERO" as &dyn fmt::Debug,
                    -1 => &"INVALID",
                    age => age,
                },
            )
            .finish()
    }
}
[src/main.rs:35] baby = Person {
    age: Age {
        age: "ZERO",
    },
}
[src/main.rs:35] tom = Person {
    age: Age {
        age: 10,
    },
}
[src/main.rs:35] inv = Person {
    age: Age {
        age: "INVALID",
    },
}

Rust Playground

Update: Age is a tuple struct instead of named struct, so it'd be better to have

impl fmt::Debug for Age {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
            0 => fmt.write_str("Age::ZERO"),
            -1 => fmt.write_str("Age::INVALID"),
            age => fmt.write_fmt(format_args!("Age({age})")),
        }
    }
}
[src/main.rs:30] baby = Person {
    age: Age::ZERO,
}
[src/main.rs:30] tom = Person {
    age: Age(10),
}
[src/main.rs:30] inv = Person {
    age: Age::INVALID,
}

Rust Playground

2 Likes

If it's possible show in debugger window but not dbg! macro?

You seem to not know what Debug in std::fmt - Rust is designed for.

dbg! calls {:#?} under the hood, which actually calls the fmt method from Debug trait and other methods from Formatter in std::fmt - Rust.

And there are various ways to use {:?} like

  • format!("{:?}", person) in your case to get a String to be passed around
  • any popular log macro supports {:?} too

My statement may be ambiguous. I mean show these as constants in lldb. instead of in the dbg! macro

emm, I know how to set this, this need custom a lldb formatter, just look this: Variable Formatting — The LLDB Debugger (llvm.org)