How to understand two named types are identical in golang

huangapple go评论81阅读模式
英文:

How to understand two named types are identical in golang

问题

type identity的规则指出:

“如果两个命名类型的类型名称源自同一个TypeSpec,则它们是相同的。”

我不太理解两个类型名称如何源自同一个TypeSpec。你能解释一下或给我一个例子吗?

英文:

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?

答案1

得分: 7

只有一种类型名称可以来自TypeSpec。这是重点。所以

type Foo int64
var x Foo
var y Foo

那么这两个Foo都来自同一个TypeSpec,所以它们是相同的Foo

然而,如果你有两个不同的文件(在不同的包中):

a.go:

type Foo int64
var x Foo

b.go:

type Foo int64
var y Foo

那么在这种情况下,这两个Foo是不相同的。尽管它们是相同的类型名称,但它们来自不同的TypeSpecs。这意味着xy的类型不相同(因此不允许使用x = y进行赋值而不进行类型转换)。

英文:

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

答案2

得分: 0

两个命名类型如果它们的类型名称源自相同的TypeSpec,则它们是相同的。

实际上,在Go代码中,你不能有两个相同的命名类型。因为在Go代码中,“源自相同的TypeSpec”意味着相同的类型。说一个类型与自身相同是没有意义的。

但是,我们确实有一些相同的不同命名类型:byte和uint8;rune和int32,根据规范。

这只在预声明类型的编译器中才可能发生。

请参考golang nuts中的讨论。

注意:
在Go 1.9中,将会有一个名为“类型别名/别名声明”的新功能。有了这个功能,可以声明不同的相同命名类型。请参考关于Go 1.9的讨论。

英文:

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

huangapple
  • 本文由 发表于 2013年11月20日 15:14:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/20089670.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定