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


Maybe via the TypeId or is there some other route?


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.


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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.