Log*_*nch 6 struct types keyword go
我一直在阅读A Tour to Go学习Go,到目前为止它一切顺利.
目前我在结构字段课上,这是右侧的示例代码:
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
v.X = 4
fmt.Println(v.X)
}
Run Code Online (Sandbox Code Playgroud)
看看第3行:
type Vertex struct {
Run Code Online (Sandbox Code Playgroud)
我不明白的是,type关键字做了什么/它为什么存在?
Eri*_*ang 10
它用于定义新类型。
一般格式:
type <new_type> <existing_type or type_definition>
常见用例:
type <new_type> <existing_type>type Seq []inttype <new_type> struct { /*...*/}type <FuncName> func(<param_type_list>) <return_type>type AdderFunc func(int, int) int在你的情况下:
它定义了一个以Vertex新结构命名的类型,以便稍后您可以通过Vertex.
该type关键字是有创建一个新的类型.这称为类型定义.新类型(在您的情况下,Vertex)将具有与基础类型(具有X和Y的结构)相同的结构.该行基本上是说"基于X int和Y int的结构创建一个名为Vertex的类型".
不要将类型定义与类型别名混淆.当您声明一个新类型时,您不只是给它一个新名称 - 它将被视为一种不同的类型.有关该主题的更多信息,请查看类型标识.