Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand two named types are identical in golang

Tags:

types

go

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?

like image 650
lianggo Avatar asked Mar 22 '23 14:03

lianggo


1 Answers

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 Foos originate in the same TypeSpec, so they are identical Foos.

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 Foos 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).

like image 73
Keith Randall Avatar answered Apr 01 '23 14:04

Keith Randall