Is there any way to only override one field when using "debug_struct"?

For example, I have a struct with a lot of fields:

struct Foo {
  a: usize,
  b: usize,
  ...
  z: usize,
}

And I want custom the debug output for only field "m", and leave other fields as the default behavior, is it possible?

Currently When I implement the Debug trait for Foo , I need to manually write all the fields:

f.debug_struct("Foo")
.field("a", &self.a)
.field("b", &self.b)
.field("c", &self.c)
...
.field("m", &"blahblah")
...
.field("y", &self.y)
.field("z", &self.z)
.finish()

which are way too cumbersome.
P.S. To use a type wrapper for field "m" and impl Debug for this new type is not acceptable in my case.

Rust-analyzer can generate the entire default Debug impl so you don't have to write it out manually. Otherwise, you can write your own macro to use instead of the built-in Debug macro.

If the field is somehow special, IMHO it would make sense to create a distinct type for it, so you can specialize Debug for that type instead of the field.

Take a look at derive_more::Debug, it might fit your use case.

2 Likes