The rules of type identity state that:
Two named types are identical if their type names originate in the same TypeSpec
I don't quite understand how two type names originate in the same TypeSpec. Can you explain it or show me an example?
Only one type name can originate from a TypeSpec. That's kind of the point. So
type Foo int64
var x Foo
var y Foo
then both Foo
s originate in the same TypeSpec, so they are identical Foo
s.
However, if you have two different files (in different packages):
a.go:
type Foo int64
var x Foo
b.go:
type Foo int64
var y Foo
Then the two Foo
s in this situation are not identical. Even though they are the same type name, they originated from different TypeSpecs. The consequence of this is that the types of x
and y
are not identical (and thus x = y
without a cast is not allowed).
Two named types are identical if their type names originate in the same TypeSpec
In fact, you can't have two named types that are identical in Go code. Because in Go code, originate in the same TypeSpec
means the same type. It's meaningless to say one type is identical to itself.
But we do have different named types which are identical: byte and uint8; rune and int32, according to the spec
It's only possible to do this in the compiler for the predeclared types.
Refer to the discussion in golang nuts
Note: In Go 1.9, there'll be a new feature called: type alias/alias declarations. With this feature, it becomes possible to declare different named types which are identical. Refer to talk about Go 1.9