上週末在台北講『Go 語言基礎課程』,其中一段介紹 Struct 的使用,發現有幾個學員對於在 Method 內要放 Pointer 或 Value 感到困惑,而我自己平時在寫 Go 語言也沒有注意到這點。好在強者學員 Dboy Liao 找到一篇說明:『Don’t Get Bitten by Pointer vs Non-Pointer Method Receivers in Golang』,在 Go 語言如何區分 func (s *MyStruct)
及 func (s MyStruct)
,底下我們先來看看簡單的 Struct 例子
package main
import "fmt"
type Cart struct {
Name string
Price int
}
func (c Cart) GetPrice() {
fmt.Println(c.Price)
}
func main() {
c := &Cart{"bage", 100}
c.GetPrice()
}
Continue reading “Go 語言內 struct methods 該使用 pointer 或 value 傳值?”