Golang method receiver type 的差異
在 Go 裡,method 的 receiver 是用 *Obj
還是用 Obj
會有不同的行為。
來個例子:
1 | type Vertex struct { |
v
可以看成像參數。
用 Vertex
就是 copy by value,caller 跟 callee 的 Vertex
instance 是不同的。
用 *Vertex
就像 C 語言 pointer 參數,本質上還是 copy by value 但因為是 pointer,所以在 moveY()
中的 v
變成是指向 caller 的那個 Vertex
instance。
基本上 method 會動到 struct 內的 field 內容都會用 pointer。習慣上當有一個 method 的 receiver 是用 pointer 時,所有 method 的 receiver 都會用 pointer。