@@ -148,18 +148,36 @@ These methods all return a `Ty<'tcx>` – note that the lifetime you get back is
148148arena that this ` tcx ` has access to. Types are always canonicalized and interned (so we never
149149allocate exactly the same type twice).
150150
151- > N.B.
152- > Because types are interned, it is possible to compare them for equality efficiently using ` == `
153- > – however, this is almost never what you want to do unless you happen to be hashing and looking
154- > for duplicates. This is because often in Rust there are multiple ways to represent the same type,
155- > particularly once inference is involved. If you are going to be testing for type equality, you
156- > probably need to start looking into the inference code to do it right.
157-
158151You can also find various common types in the ` tcx ` itself by accessing its fields:
159152` tcx.types.bool ` , ` tcx.types.char ` , etc. (See [ ` CommonTypes ` ] for more.)
160153
161154[ `CommonTypes` ] : https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/context/struct.CommonTypes.html
162155
156+ <!-- N.B: This section is linked from the type comparison internal lint. -->
157+ ## Comparing types
158+
159+ Because types are interned, it is possible to compare them for equality efficiently using ` == `
160+ – however, this is almost never what you want to do unless you happen to be hashing and looking
161+ for duplicates. This is because often in Rust there are multiple ways to represent the same type,
162+ particularly once inference is involved.
163+
164+ For example, the type ` {integer} ` (an integer inference variable, the type of an integer
165+ literal like ` 0 ` ) and ` u8 ` should often be treated as equal when testing whether they
166+ can be assigned to each other (which is a common operation in diagnostics code).
167+ ` == ` on them will return ` false ` though, since they are different types.
168+
169+ The simplest way to compare two types correctly requires an inference context (` infcx ` ).
170+ If you have one, you can use ` infcx.can_eq(ty1, ty2) ` to check whether the types can be made equal,
171+ so whether they can be assigned to each other.
172+ When working with an inference context, you have to be careful to ensure that potential inference
173+ variables inside the types actually belong to that inference context. If you are in a function
174+ that has access to an inference context already, this should be the case.
175+
176+ Another consideration is normalization. Two types may actually be the same, but one is behind an associated type.
177+ To compare them correctly, you have to normalize the types first. <!-- FIXME: When do you have to worry about this? When not? -->
178+
179+ <!-- What to do when you don't have an inference context available already? Just create one and hope all goes well? -->
180+
163181## ` ty::TyKind ` Variants
164182
165183Note: ` TyKind ` is ** NOT** the functional programming concept of * Kind* .
0 commit comments