Skip to content

Commit 1c36bb2

Browse files
committed
add docs note about Any::type_id on smart pointers
1 parent fa55f66 commit 1c36bb2

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

library/core/src/any.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,29 @@
1414
//!
1515
//! [`Box`]: ../../std/boxed/struct.Box.html
1616
//!
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+
//!
1740
//! # Examples
1841
//!
1942
//! Consider a situation where we want to log out a value passed to a function.

0 commit comments

Comments
 (0)