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.
Debug
fordyn Node
, instead of implementDebug
for every concrete type?impl<T: Node> fmt::Debug for T
at which point you can usestd::any::type_name::<Self>()
to get the type name.