Type identity

May 25, 2023

Type identity

Two types are either identical or different.

Well now that’s profound, isn’t it? LOL.

The real point is that there are not different “degrees of similarity.”

The spec continues…

A named type is always different from any other type. Otherwise, two types are identical if their underlying type literals are structurally equivalent; that is, they have the same literal structure and corresponding components have identical types.

So the rules for type identity are rather simple. Although tomorrow we’ll dive into the specific implications of the rules.

Any named type is different from all other types, regardless of the underlying type. (A caveat is type aliases, which we’ll get to later, and allows multiple identifiers to point to a single type.)

Unnamed types (such as unnamed slices, arrays, structs, interfaces, etc) are identical if they have the same recursive structure.

Therefore, these two struct types are different, even though they have the same fields and types, because their structure is different (the fields are reversed):

struct {
	Name string
	Age  int
}

struct {
	Age int
	Name string
}

Quotes from The Go Programming Language Specification Version of December 15, 2022

Share this