【问题标题】:What (exactly) does the type keyword do in go?type 关键字在 go 中(确切地)做了什么?
【发布时间】:2019-05-10 10:14:05
【问题描述】:

我一直在阅读A Tour of Go 以了解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 关键字有什么作用,为什么会出现?

【问题讨论】:

    标签: go struct types keyword


    【解决方案1】:

    type 关键字用于创建新类型。这称为type definition。新类型(在您的情况下为 Vertex)将具有与基础类型(具有 X 和 Y 的结构)相同的结构。该行基本上是在说“基于 X int 和 Y int 的结构创建一个名为 Vertex 的类型”。

    不要将类型定义与类型别名混淆。当你声明一个新类型时,你不仅仅是给它一个新名字——它会被认为是一个不同的类型。请查看type identity,了解有关该主题的更多信息。

    【讨论】:

    • 另外,如果你有一个类型 A 和一个方法 B。如果您将另一个类型C 定义为type C A,您将无法在类型C 上调用方法B。那就是var c C; c.B() 不会编译。见play.golang.org/p/bocCzDqu3lh
    【解决方案2】:

    用于定义新类型。

    一般格式:
    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引用该结构。

    【讨论】:

      【解决方案3】:

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

      使用 type 关键字就像在 GO 中创建类一样

      示例输入结构

      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 stringintfloat 相同)

         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 关键字构建的类型肯定可以有不止一种方法

      如果我错了,请纠正我

      【讨论】:

        猜你喜欢
        • 2020-12-31
        • 2011-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-28
        • 1970-01-01
        • 2016-10-24
        相关资源
        最近更新 更多