如何理解golang中的两个命名类型是相同的 [英] How to understand two named types are identical in golang
问题描述
类型标识规定:
如果两个命名类型的名称源于相同的TypeSpec
不太了解两个类型名称是如何在相同的TypeSpec中产生的。你可以解释一下或者给我看一个例子吗? 只有一个类型名可以源自TypeSpec。这点很重要。所以
type Foo int64
var x Foo
var y Foo
然后 Foo
s起源于相同的TypeSpec,因此它们是相同的 Foo
s。
然而,如果你有两个不同的文件(不同的包):
ba.go:
type Foo int64
var x Foo
b.go:
type Foo int64
var y Foo
然后两个 Foo
在这种情况下并不完全相同。尽管它们是相同的类型名称,但它们起源于不同的TypeSpecs。其结果是, x
和 y
的类型不相同(因此 x = y
不允许)。
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).
这篇关于如何理解golang中的两个命名类型是相同的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!