How to debug &Any issues?

Is there a general technique to figuring out the actual type of a &dyn Any reference while debugging?

I just spent the afternoon debugging a case where a downcast_ref::<T> of a &dyn Any failed to unwrap because it was a &Box<T> instead of a &T. It would have been much faster to debug if there was a way to print out the actual type of the &dyn Any. The bug was because the assignment:

 fn foo(y: &Box<dyn Any>) {
   let x: &dyn Any = y;
...

compiles but doesn't deref the Box - one needs to assign &**y instead. Unlike other cases of &Box<T> assigned to a &T variable, which do deref the Box. Which is somehow both expected and weird. If I was able to print out the actualy type and saw Box, I would have known exactly what was going on.

1 Like

You can make a subtrait, but it's a pain to cover everything (like being able to get to a Box<dyn Any> so you can downcast) without supertrait upcasting.[1]

It's not Box or Any specific, for whatever that's worth. Just coercion order precedence or such.

Incidentally there's usually no reason to take &Box<T> (similar to &Vec<T>). You could just take &dyn Any as the argument. (You'll have the same &**bx issues at the call site though.)


  1. which is an unstable feature ↩ī¸Ž

3 Likes