Golang 挖坑之旅——类型理解
0. 问题描述
参考官网文档来理解type
时,遇上了一些模糊的概念问题,在此开一篇文章作为记录使用,涉及概念named type
、unnamed type
、alias declaration
、type definition
、underlying type
、defined type
。
注:通篇整英文单词是因为很多中文的翻译各个地方都有所差异。
1. Type Declaration
A type declaration binds an identifier, the type name, to a type. Type declarations come in two forms: alias declarations and type definitions.
官网对于类型的声明有两种,一种是alias declaration
,另一种是type definition
,这两种有非常大的区别,先用一个简短的例子展示:
// alias declaration
type (
nodeList = []*Node // nodeList and []*Node are identical types
Polar = polar // Polar and polar denote identical types
)
// type definition
type (
Point struct{
x, y float64 } // Point and struct{ x, y float64 } are different types
polar Point // polar and Point denote different types
)
二者在产生的类型和source type
的关系上,上有本质区别,alias
不产生新的type
,而通过type definition
得到的defined type
,不论source type
是啥,全都是不一样的。