但是,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 是比較有效率的選擇。