Debug wrapper for closure

I have some struct that has a generic parameter which (in most cases) will be a closure.
I still want to be able to derive Debug for it so I decided to put the values with the generic type behind some kind of debug wrapper.
Now using the debug wrapper directly works, but not when its part of another type?

Am I missing something or is there a reason why this doesn't work?
I know I could restructure the types so that the DebugWrapper becomes part of the generic type, but right now I'm mostly curious

#[derive(Debug)]
enum Test<T>{
    A(DebugWrapper<T>),
}

struct DebugWrapper<T>(T);

use core::fmt;
impl<T> fmt::Debug for DebugWrapper<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DebugWrapper").finish()
    }
}

fn main(){
    //works
    println!("{:?}",DebugWrapper(|| 1u8));
    //does not work
    //println!("{:?}",Test::A(DebugWrapper(|| 1u8)));
}

This is a known bug:

Instead of Debug emitting an empty DebugWrapper {} you may want to print std::any::type_name::<T>(). Usually a closure's type name will contain information about where it was defined and sometimes what variables it captured.

use std::fmt::{self, Debug, Formatter};

pub struct DebugWrapper<T>(T);

impl<T> Debug for DebugWrapper<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", std::any::type_name::<T>())
    }
}

fn main() {
    println!("{:?}", DebugWrapper(()));
    println!("{:?}", DebugWrapper(main));
    println!("{:?}", DebugWrapper(std::env::vars));
    println!("{:?}", DebugWrapper(|x: usize| {}));
    let y = 0;
    println!(
        "{:?}",
        DebugWrapper(async {
            println!("{}", y);
        })
    );
}

outputs

()
playground::main
std::env::vars
playground::main::{{closure}}
core::future::from_generator::GenFuture<playground::main::{{closure}}>

(playground)

2 Likes

In my case the type wont contain information were it was defined as it is a dyn Fn(), but I will still use it, as its better than nothing :slight_smile:
And since I'm not building the types by hand (it gets built by a macro) I might just extract the information where it comes from at that place and save it inside the struct.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.