1

I'm implementing the Debug trait on a trait. I'd like to be able to display the name of the concrete type that implements this particular instance of the trait.

trait Node {
    foo: String,
}
    
impl fmt::Debug for dyn Node {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = // get type name of self here
        write!(f, "The name: {}", name);
    }
}

I've read a number of posts about Any and downcasting and whatnot, but these solutions seem complex.

One possible solution is to add a method to the trait itself: get_name() -> String, and implement it for each struct individually. There has to be a simpler way, though.

3
  • 1
    Why you want to implement Debug for dyn Node, instead of implement Debug for every concrete type? Commented Nov 12, 2022 at 1:17
  • @PengGuanwen So I can implement it once instead of two dozen times.
    – ccleve
    Commented Nov 12, 2022 at 2:55
  • 1
    @ccleve the right way to "implement it once instead of two dozen times" is to impl<T: Node> fmt::Debug for T at which point you can use std::any::type_name::<Self>() to get the type name.
    – Jmb
    Commented Nov 12, 2022 at 6:58

1 Answer 1

6

We could add a get_name method to Node which returns whatever the name of Self is using std::any::type_name::<Self>().

trait Node {
    fn get_name(&self) -> &'static str {
        return std::any::type_name::<Self>();
    }
}

Inside the Debug implementation we can call self.get_name().

impl fmt::Debug for dyn Node {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = self.get_name();
        write!(f, "The name: {}", name)
    }
}

Printing a dyn Node instance will show the following result:

struct SomeStruct {}
impl Node for SomeStruct {} 

fn main() {
    let a: Box<dyn Node> = Box::new(SomeStruct {});

    println!("{:?}", a)
    // The name: playground::SomeStruct
}

Playground

1
  • Note that, while this is not necessarily an issue, if you impl the trait for dyn Trait it'll not show the real type. Commented Aug 29, 2023 at 18:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.