[英]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 <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
引用結構。
實際上 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 類型移動(對於int或float相同)
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
}
struct和string、int、float之間的區別只是在struct 中,您可以使用任何不同的數據類型添加更多屬性
相反,在字符串、整數、浮點數中,您只能有 1 個屬性,在您啟動類型時創建(例如:animal_cow := Animal("Cow")
但是,使用 type 關鍵字構建的所有類型肯定可以有 1 個以上的方法
糾正我,如果我錯了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.