Skip to content

Stdlib docs: Add note about getting TypeId of Box<dyn Any> ? #79868

Closed
@sharnoff

Description

@sharnoff

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>>());

playground link

Metadata

Metadata

Assignees

Labels

A-DSTsArea: Dynamically-sized types (DSTs)A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions