golang筆記之指針使用

Choosing a value or pointer receiver

There are two reasons to use a pointer receiver.

  • The first is so that the method can modify the value that its receiver points to.

  • The second is to avoid copying the value on each method call. This can be more efficient if the receiver is a large struct, for example.

package main

import (
    "fmt"
    "math"
)

type Vertex struct {
    X, Y float64
}

func (v *Vertex) Scale(f float64) {
    v.X = v.X * f
    v.Y = v.Y * f
}

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

func main() {
    v := &Vertex{3, 4}
    fmt.Printf("Before scaling: %+v, Abs: %v\n", v, v.Abs())
    v.Scale(5)
    fmt.Printf("After scaling: %+v, Abs: %v\n", v, v.Abs())
}

In this example, both Scale and Abs are with receiver type *Vertex, even though the Abs method needn't modify its receiver.

In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both. (We'll see why over the next few pages.)

參考:
https://tour.golang.org/methods/8

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,847評(píng)論 0 10
  • 標(biāo)簽(空格分隔): 編程 Go官方文檔 Using the tour 1.1 Hello, 世界 Welcome...
    uangianlap閱讀 1,639評(píng)論 0 5
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,059評(píng)論 0 23
  • 我們?cè)诳旃?jié)奏的生活里。似乎希望結(jié)果也是快餐化,可以快速的看到自己想要的結(jié)果。 談戀愛(ài)急著想要結(jié)婚,結(jié)了婚張快點(diǎn)要寶...
    起飛瞬間閱讀 139評(píng)論 0 0
  • 在生活中,沒(méi)有任何東西比人的行動(dòng)更重要、更珍奇了。 01 時(shí)隔一年后,我又再一次開(kāi)始寫(xiě)作,內(nèi)心很忐忑,很害怕會(huì)又再...
    大方柒柒閱讀 704評(píng)論 0 4

友情鏈接更多精彩內(nèi)容