Skip to content

Commit f6b6d5c

Browse files
committed
Auto merge of #79870 - sharnoff:smart-pointer-Any-type_id, r=shepmaster
Add docs note about `Any::type_id` on smart pointers Fixes #79868. There's an issue I've run into a couple times while using values of type `Box<dyn Any>` - essentially, calling `value.type_id()` doesn't dereference to the trait object, but uses the implementation of `Any` for `Box<dyn Any>`, giving us the `TypeId` of the container instead of the object inside it. I couldn't find any notes about this in the documentation and - while it could be inferred from existing knowledge of Rust and the blanket implemenation of `Any` - I think it'd be nice to have a note about it in the documentation for the `any` module. Anyways, here's a first draft of a section about it. I'm happy to revise wording :)
2 parents 0876f59 + 72a7f73 commit f6b6d5c

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Diff for: library/core/src/any.rs

+23
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*, not the underlying trait object. This can be avoided by
23+
//! converting the smart pointer into a `&dyn Any` instead, which will return
24+
//! the object's `TypeId`. For example:
25+
//!
26+
//! ```
27+
//! use std::any::{Any, TypeId};
28+
//!
29+
//! let boxed: Box<dyn Any> = Box::new(3_i32);
30+
//!
31+
//! // You're more likely to want this:
32+
//! let actual_id = (&*boxed).type_id();
33+
//! // ... than this:
34+
//! let boxed_id = boxed.type_id();
35+
//!
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)