问题:
我最近开始阅读 Golang Specification Manual并且在试图理解 relevant section 中的 named 和 unnamed 类型时遇到了困难。 .我来自动态语言,这让我有点头疼。
手册说明:
A type determines the set of values and operations specific to values of that type. Types may be named or unnamed. Named types are specified by a (possibly qualified) type name; unnamed types are specified using a type literal, which composes a new type from existing types.
然后继续:
Named instances of the boolean, numeric, and string types are predeclared. Composite types—array, struct, pointer, function, interface, slice, map, and channel types—may be constructed using type literals.
这里的问题是,在规范中,链接让我在页面之间跳来跳去,忘记了这么多概念向我抛出的太快是什么。
其他资源:
我已经四处寻找澄清这一点,除了规范手册,资源稀缺。我能找到的唯一相关 Material 是:
Learning Go - Types - 博客文章解释 Go 中类型系统的细微差别。
An issue here关于和我问的差不多。
很遗憾,我找不到任何 relevant questions 在 Stack Overflow 上与此有关。 (如果它们存在,我需要修改我的搜索方法!)。我之所以这么问,是因为理解一门新语言的类型系统是基本概念之一,以便有效地学习它。
那么,问题来了:
谁能提供一个简洁明了的例子来说明命名类型和未命名类型的概念之间的区别?*
*另外,解释qualified和pre-declared的概念有利于完整性,但显然没有必要。
最佳答案
一种简单的思考方式是,命名类型是您使用 type
语句定义的类型,而未命名类型是由类型文字定义的复合类型。
例如变量x
的类型是未命名的:
var x struct{ I int }
并且变量y
的类型命名为:
type Foo struct{ I int }
var y Foo
这些变量中的每一个都被认为具有不同的类型,即使每个变量的底层类型相同(一个包含一个名为 I
的整数成员的结构)。
未命名类型的一个属性是使用相同未命名类型声明的所有变量都被认为具有相同类型,而具有相同底层表示的两个命名类型是不同的。例如:
var x2 struct{ I int }
type Bar struct{ I int }
var z Bar
这里 x
和 x2
具有相同的类型,而 y
和 z
没有。
这些区别在语言中的一些地方发挥作用:
禁止将一种命名类型的值分配给不同命名类型的变量,即使底层类型相同。但是,允许在相关的命名类型和未命名类型之间进行分配。也就是说,以下是可以的:
x = y // named type assigned to unnamed type y = x // unnamed type assigned to named type
但以下是错误:
y = z // assignment between different named types
您可以为已命名的类型定义方法。因此,向
Foo
添加方法是可能的,但您无法将方法附加到变量x
。
还请注意,命名类型可以在类型文字中用于定义新的未命名类型。例如,尽管使用了 Foo
,但 slice 类型 []Foo
是未命名的。如果我们想将方法附加到这种 slice 类型(例如,与 sort
包一起使用),我们必须命名它:
type Baz []Foo
关于types - 命名和未命名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32983546/