Type identities of other types

May 30, 2023

Type identity

  • Two pointer types are identical if they have identical base types.

Given:

type (
	P = *int
	Q = P
	R *int
)

P, Q, and *int are all identical to each other, but different from *int32 and R.

  • Two function types are identical if they have the same number of parameters and result values, corresponding parameter and result types are identical, and either both functions are variadic or neither is. Parameter and result names are not required to match.

Given:

type (
	F1 = func(x, y int) error
	F2 = func(int, int) error
	F3 = func([]int)
	F4 = func(...int)
)
  • F1 and F2 are identical (parameter and result names are not required to match)
  • F3 and F4 are different, because only one is variadic, even though the number and type of parameters is otherwise the same.
  • Two interface types are identical if they define the same type set.

Notably, this differs from struct identity, in that the order of method declaration is unimportant. Therefore, given:

type (
	I1 = interface {
		Foo()
		Bar()
	}
  I2 = interface {
		Bar()
		Foo()
	}
)

I1 and I2 are identical, becasue they define the same type set.

  • Two channel types are identical if they have identical element types and the same direction.

Given:

type (
	C1 = chan int
  C2 = chan<- int
  C3 = <-chan int
)

C1, C2, and C3 are all different from each other, even though, interestingly, they may represent the exact same value!

  • Two instantiated types are identical if their defined types and all type arguments are identical.

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

Share this