Skip to content

TypeId documentation should mention gotcha re covariant subtypes #89150

Closed
@uazu

Description

@uazu

A covariant subtype gets a different type-ID, but can be converted freely from one to the other. This means that taking a type-ID of a generic type argument in a type's new method is not guaranteed to give the same type-ID that the type will eventually be called with. The solution is to force the generic type argument to be invariant using PhantomData. See this bug in qcell crate.

It would be helpful if this were documented to avoid similar bugs occurring in other crates.

use std::any::TypeId;
fn main() {
    println!(
        "{:?}, {:?}",
        TypeId::of::<fn(&'_ ())>(),
        TypeId::of::<fn(&'static ())>(),
    );
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsT-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