File tree 1 file changed +23
-0
lines changed
1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change 14
14
//!
15
15
//! [`Box`]: ../../std/boxed/struct.Box.html
16
16
//!
17
+ //! # Smart pointers and `dyn Any`
18
+ //!
19
+ //! One piece of behavior to keep in mind when using `Any` as a trait object,
20
+ //! especially with types like `Box<dyn Any>` or `Arc<dyn Any>` is that simply
21
+ //! calling `.type_id()` on the value will produce the `TypeId` of the
22
+ //! container, and not the underlying trait object. This can be avoided
23
+ //! converting the smart pointer into a `&dyn Any` instead, which will return
24
+ //! the object's type id. For example:
25
+ //! ```
26
+ //! use std::any::{Any, TypeId};
27
+ //!
28
+ //! let boxed: Box<dyn Any> = Box::new(3_i32);
29
+ //!
30
+ //! // You're more likely to want this:
31
+ //! let actual_id = (&*boxed).type_id();
32
+ //! // ... than this:
33
+ //! let boxed_id = boxed.type_id();
34
+ //!
35
+ //! // Both of these assertions pass
36
+ //! assert_eq!(actual_id, TypeId::of::<i32>());
37
+ //! assert_eq!(boxed_id, TypeId::of::<Box<dyn Any>>());
38
+ //! ```
39
+ //!
17
40
//! # Examples
18
41
//!
19
42
//! Consider a situation where we want to log out a value passed to a function.
You can’t perform that action at this time.
0 commit comments