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

What (exactly) does the type keyword do in go?

我一直在阅读 A Tour of Go to learn Go-Lang,目前进展顺利。

我目前正在上 Struct Fields 课,这是右侧的示例代码:

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 关键字有什么作用,为什么会出现?

type 关键字用于创建新类型。这叫做type definition。新类型(在您的例子中为 Vertex)将具有与基础类型(具有 X 和 Y 的结构)相同的结构。该行基本上是在说 "create a type called Vertex based on a struct of X int and Y int".

不要混淆类型定义和类型别名。当您声明一个新类型时,您不仅仅是给它一个新名称——它将被视为一个独特的类型。查看 type identity 了解有关该主题的更多信息。

用于定义新类型。

通用格式:
type <new_type> <existing_type or type_definition>

常见用例:

  • 为现有类型创建新类型。
    格式:
    type <new_type> <existing_type>
    例如
    type Seq []int
  • 定义结构时创建类型。
    格式:
    type <new_type> struct { /*...*/}
    例如
    https://gobyexample.com/structs
  • 定义函数类型,(也就是通过为函数签名指定名称)
    格式:
    type <FuncName> func(<param_type_list>) <return_type>
    例如
    type AdderFunc func(int, int) int

你的情况:

它为一个新的结构定义了一个名为Vertex的类型,这样以后你就可以通过Vertex引用这个结构。

实际上类型关键字与 PHP 中的 class 拓扑相同。

使用 type 关键字就像在 GO 中创建 class

示例 键入结构

type Animal struct {
  name string //this is like property
}

func (An Animal) PrintAnimal() {
  fmt.Println(An.name) //print properties
}

func main() {
  animal_cow := Animal{ name: "Cow"} // like initiate object

  animal_cow.PrintAnimal() //access method
}

好的,让我们使用 type string(与 intfloat 相同)

   type Animal string
        
   // create method for class (type) animal
   func (An Animal) PrintAnimal() {
      fmt.Println(An) //print properties
   }
    
   func main(){
      animal_cow := Animal("Cow") // like initiate object
    
      animal_cow.PrintAnimal() //access method
      //Cow
   }

structstring, int, float 的区别就在 struct 你可以添加具有任何不同数据类型的更多属性

string, int, float 相反,您只能拥有 1 个属性,这些属性是在您启动类型时创建的(例如:animal_cow := Animal("Cow ")

但是,所有使用 type 关键字构建的类型肯定可以有不止一种方法

如有错误请指正