Description
Hello! There's an issue that I've run into a couple times using std::any::Any
, and I figured it would be nice to have a small section in the documentation for the module about this particular behavior.
Essentially, when we have a value of type Box<dyn Any>
, and we'd like to check the type id of the underlying value (i.e. not the type id of Box<dyn Any>
), we can't just use value.type_id()
. The nicest solution I've found is to use (&*value).type_id()
, so that we're correctly calling the method on a value of type &dyn Any
.
In theory, this applies to all other smart pointers as well; the work I'm doing just happens to only have boxes. The distinction here becomes painful with assertions: it's very easy to write assert_eq!(boxed.type_id(), expected_type_id)
and get panics, without immediately realizing that the problem is the assertion itself.
I think it'd be nice to mention this particular quirk in the module documentation for std::any
. I'm not sure what the general opinion on that would be, though - I wanted to get some feedback before submitting a PR for it.
Example:
use std::any::{Any, TypeId};
let boxed: Box<dyn Any> = Box::new(0_i32);
let boxed_id = boxed.type_id();
let actual_id = (&*boxed).type_id();
// Both of these assertions pass
assert_eq!(actual_id, TypeId::of::<i32>());
assert_eq!(boxed_id, TypeId::of::<Box<dyn Any>>());