type 关键字在 go 中(究竟)做了什么?

我一直在阅读Go Tour of Go来学习Go-Lang,到目前为止进展顺利。

我目前正在学习结构字段课程,这是右侧的示例代码:

package main


import "fmt"


type Vertex struct {

  X int

  Y int

}


func main() {

  v := Vertex{1, 2}

  v.X = 4

  fmt.Println(v.X)

}

看一下第 3 行:


type Vertex struct {

我不明白的是,type关键字是做什么的,为什么会在那里?


陪伴而非守候
浏览 127回答 3
3回答

慕哥6287543

关键字type用于创建新类型。这称为类型定义。新类型(在您的例子中为 Vertex)将具有与基础类型(具有 X 和 Y 的结构)相同的结构。该行基本上是在说“基于 X int 和 Y int 的结构创建一个名为 Vertex 的类型”。不要混淆类型定义和类型别名。当您声明一个新类型时,您不仅仅是给它一个新名称——它将被视为一个独特的类型。查看类型标识以获取有关该主题的更多信息。

幕布斯6054654

它用于定义新类型。一般格式:type <new_type> <existing_type or type_definition>常见用例:为现有类型创建新类型。格式:type <new_type> <existing_type>如type Seq []int在定义结构时创建类型。格式:type <new_type> struct { /*...*/}定义函数类型,(也就是通过将名称分配给函数签名)。格式:type <FuncName> func(<param_type_list>) <return_type>如type AdderFunc func(int, int) int在你的情况下:它定义了一个以新结构命名的类型Vertex,以便稍后您可以通过 引用该结构Vertex。

慕桂英3389331

实际上 type 关键字与 PHP 中的类拓扑相同。使用 type 关键字就像在 GO 中创建类一样结构中的示例类型type Animal struct {&nbsp; name string //this is like property}func (An Animal) PrintAnimal() {&nbsp; fmt.Println(An.name) //print properties}func main() {&nbsp; animal_cow := Animal{ name: "Cow"} // like initiate object&nbsp; animal_cow.PrintAnimal() //access method}好的,让我们移动字符串类型(对于int或float是相同的)&nbsp; &nbsp;type Animal string&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp;// create method for class (type) animal&nbsp; &nbsp;func (An Animal) PrintAnimal() {&nbsp; &nbsp; &nbsp; fmt.Println(An) //print properties&nbsp; &nbsp;}&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;func main(){&nbsp; &nbsp; &nbsp; animal_cow := Animal("Cow") // like initiate object&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; animal_cow.PrintAnimal() //access method&nbsp; &nbsp; &nbsp; //Cow&nbsp; &nbsp;}struct和string、int、float之间的区别仅在struct中您可以添加具有任何不同数据类型的更多属性在string、int、float中相反,您只能拥有 1 个属性,这些属性是在您启动类型时创建的(例如:animal_cow := Animal("Cow")但是,所有使用 type 关键字构建的类型都可以有不止一种方法如果我错了请纠正我
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go