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(())
}
}
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With