Golang — receiver and call-by-value

Zack
2 min readAug 26, 2018

golang 中有一個很像物件導向語言的架構,大概是長這樣:

type Buffer struct {
id int
context int
}
func (b Buffer) process() {

}

但是,golang 在實作上有個不一樣的地方。

在物件導向程式語言中,可以很輕易地寫出修改class member 的 method,但是在 golang 中就要注意一下。

func (b Buffer) process() {
b.context += 1
}

上例對於 receiver 成員的操作,只存在於這個 function。function 結束之後,這些變動也跟著消失。

原因在於 receiver 和其他參數一樣是 call by value,是只存在於 stack 中的一個副本。想要操作內容的話必須傳入 address,對address 指向的物件作操作才行。

像是這樣:

func (b *Buffer) process() {
b.context += 1
}

因為這樣的差異,receiver 架構較大的話,使用 non-pointer method receiver 也會導致更長的copy 時間,pointer method receiver 是比較有效率的選擇。

--

--

Zack

There is a saying goes, “Programmers should blog.”