簡體   English   中英

type 關鍵字在 go 中(確切地)做了什么?

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

我一直在閱讀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關鍵字有什么作用,為什么會在那里?

type關鍵字用於創建新類型。 這稱為類型定義 新類型(在您的情況下,Vertex)將具有與基礎類型(具有X和Y的結構)相同的結構。 該行基本上是說“基於X int和Y int的結構創建一個名為Vertex的類型”。

不要將類型定義與類型別名混淆。 當您聲明一個新類型時,您不只是給它一個新名稱 - 它將被視為一種不同的類型。 有關該主題的更多信息,請查看類型標識

它用於定義新類型。

一般格式:
type <new_type> <existing_type or type_definition>

常見用例:

  • 為現有類型創建新類型。
    格式:
    type <new_type> <existing_type>
    例如
    type Seq []int
  • 定義struct時創建一個類型。
    格式:
    type <new_type> struct { /*...*/}
    例如
    https://gobyexample.com/structs
  • 定義函數類型(也就是說,通過為函數簽名指定名稱)
    格式:
    type <FuncName> func(<param_type_list>) <return_type>
    例如
    type AdderFunc func(int, int) int

在你的情況下:

它為新結構定義了一個名為Vertex的類型,以便稍后可以通過Vertex引用結構。

實際上 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
}

OK 讓我們使用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 中,您可以使用任何不同的數據類型添加更多屬性

相反,在字符串、整數、浮點數中,您只能有 1 個屬性,在您啟動類型時創建(例如:animal_cow := Animal("Cow")

但是,使用 type 關鍵字構建的所有類型肯定可以有 1 個以上的方法

糾正我,如果我錯了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM