Type identities of compound types
May 29, 2023
So we now know that types are either identical or different. let’s look at the details, with examples.
Type identity
… In detail:
- Two array types are identical if they have identical element types and the same array length.
So given:
type (
X = [10]int
Y = X
Z [10]int
)
Types X
, Y
, and [10]int
are identical to each other, but not to [9]int
or [10]int32
. Type Z
is also different from all the others, due to the fact that it is a named type.
Note that X
and Y
are not actually named types; the equal sign (=
) indicates that they are aliases to the unnamed type [10]int
.
- Two slice types are identical if they have identical element types.
Given:
type(
A0 = []string
A1 = A0
AZ []string
)
Types A0
, A1
and []string
are identical to each other, but not to []int
or AZ
.
- Two struct types are identical if they have the same sequence of fields, and if corresponding fields have the same names, and identical types, and identical tags. Non-exported field names from different packages are always different.
Therefore:
struct{ Name string, Age int }
is different fromstruct{ Age int, Name string }
because the sequence of fields differs.struct{ Name string, Age int }
is different fromstruct{ Fullname string, Age int }
because field names differ.struct{ Name string, Age int }
is different fromstruct{ Name string, Age uint }
because field types differ.struct{ Name string `json:"name"`, Age int }
is different fromstruct{ Name string, Age int }
because struct tags differ.struct{ name string }
defined in packagefoo
is different fromstruct{ name string }
defined in packagebar
.
And jumping out of order a bit…
- Two map types are identical if they have identical key and element types.
Given:
type (
M1 = map[string]any
M2 = map[string]string
)
M1
and M2
are different. The empty interface is a distinct type, and does not act as a wildcard in compound types such as maps.
Quotes from The Go Programming Language Specification Version of December 15, 2022