Determine type identity and underlying types
Determine type identity and underlying types
A defined type is distinct from other defined types, even when their underlying types match. An alias denotes an existing type. The underlying type describes the representation in terms of other types; it is not permission to assign every value with that representation. Unnamed composite types have structural identity rules.
package main
import ( "fmt" "reflect")
type A inttype B inttype Alias = A
func main() { fmt.Println(reflect.TypeOf(A(1)) == reflect.TypeOf(B(1))) fmt.Println(reflect.TypeOf(A(1)) == reflect.TypeOf(Alias(1)))}Reflect.TypeOf exposes dynamic type identity here. A and B have underlying int but different identities. Alias and A are identical. These checks do not measure memory layout.
Expected output:
falsetrueCompare unnamed struct types
package main
import ( "fmt" "reflect")
func main() { a := struct { X int `json:"x"` }{X: 1} b := struct { X int `json:"y"` }{X: 1} fmt.Println(reflect.TypeOf(a) == reflect.TypeOf(b)) fmt.Println(reflect.TypeOf([2]int{}) == reflect.TypeOf([3]int{}))}Struct identity depends on field order, names, types, tags and embedding; unexported names from different packages are distinct. Array length participates in identity. Do not equate identical-looking values with identical types.
Expected output:
falsefalseTry it locally
Define IDs as []int and Alias = IDs. Compare their reflection types with each other and with []int.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced type semantics 01: Determine type identity and underlying types
Check the lesson objective before moving on.
Do distinct defined types with underlying int have identical identity?
Which participates in unnamed array type identity?