Get the `DefId` for a `Ty`

This document indicates that every rustc_middle::ty::Ty has a corresponding (unique) DefId. Can someone tell me how I can get the DefId from either the Ty or the TyKind?

For example, is there some API to extract the DefId that corresponds to

rustc_middle::ty::TyKind::Bool

Maybe via the TypeId or is there some other route?

Thanks!

1 Like

For every type defined in the source code, there is a unique DefId (see this chapter).

This only applies for types defined in the source code (TyKind::Adt). It doesn't apply to primitive types. Primitive types don't have an associated DefId.

2 Likes

To add to what bjorn3 said, if you need to check if a given Ty corresponds to bool, you can Eq it against tcx.types.bool. There are also methods defined in either TyS (type Ty = &'tcx TyS<'tcx>;) or TyKind (can't recall which of the top of my head) that let you ask what the type is (is_primitive/is_numeric/etc.).

Thank you very much @bjorn3 and @ekuber !

I mentioned Bool just as an example, I'm just as interested in the others e.g. the AdtDef case, but there I see that there is already a public field with the DefId.

Thanks again!

1 Like