簡體   English   中英

入門:在struct上調用方法和在指向該struct的指針上調用它之間有什么區別?

[英]Go basics: What is the diference between calling a method on struct and calling it on a pointer to that struct?

支持我具有Vertex類型

type Vertex struct {
    X, Y float64
}

我定義了一個方法

func (v *Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

這兩個電話有什么區別? (它們都返回相同的結果)

v1 := Vertex{3, 4}
fmt.Println(v1.Abs())

v2 := &Vertex{3, 4}
fmt.Println(v2.Abs())

第一個版本相當於

var v1 Vertex
v1.X = 3
v1.y = 4
fmt.Println((&v1).Abs)

第二個版本相當於

var v2 *Vertex
v2 = new(Vertex)
v2.X = 3
v2.y = 4
fmt.Println(v2.Abs)

因此,唯一的實質區別是v1是一個值,而v2是一個指向Vertex類型的值的指針。

暫無
暫無

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

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