7

When deriving Debug, what is the best approach to skip a specific struct field that doesn't implement Debug? For example:

#[derive(Debug)] pub struct MySettings { pub max_size: usize, pub max_queue_size: usize, // this guy doesn't implement Debug pub my_type: Box<dyn MyType + Send + Sync> } 

I can't add a crate to the Cargo.toml.

Right now I am providing a blank impl for that field like this:

impl std::fmt::Debug for (dyn MyType + Send + Sync){ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Ok(()) } } 
2
  • There is this question for generics and this question for Fn. tl;dr you can't derive your Debug with the standard macros. Commented Aug 14, 2024 at 12:42
  • 1
    I suspect the best approach will be to impl Debug manually, rather than using the derive macro. Commented Aug 14, 2024 at 12:42

1 Answer 1

10

You will need to implement Debug manually, but if you want to be maximally lazy, you can still essentially get Rust to derive it for you. You can create a struct inside the Debug implementation and give it the same name, MySettings, and choose which fields it contains.

use std::fmt; pub struct MyType; pub struct MySettings { pub max_size: usize, pub max_queue_size: usize, // this guy doesn't implement Debug pub my_type: Box<MyType>, } impl fmt::Debug for MySettings { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { #[derive(Debug)] struct MySettings<'a> { max_size: &'a usize, max_queue_size: &'a usize, } let Self { max_size, max_queue_size, my_type: _, } = self; // per Chayim Friedman’s suggestion fmt::Debug::fmt(&MySettings { max_size, max_queue_size }, f) } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of the write!(), better to forward it: fmt::Debug::fmt(&MySettings { ... }, f).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.