Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip struct field when deriving Debug [duplicate]

Tags:

rust

derive

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(())
    }
}
like image 503
diogopontual Avatar asked Jun 19 '26 21:06

diogopontual


1 Answers

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)
    }
}
like image 175
BallpointBen Avatar answered Jun 23 '26 08:06

BallpointBen