使用範例
// use pointers
type CoffeeMachine struct {
NumberOfCoffeeBeans int
}
func NewcoffeeMachine() *CoffeeMachine {
return &CoffeeMachine{}
}
func (cm *CoffeeMachine) SetNumberOfCoffeeBeans(n int) {
cm.NumberOfCoffeeBeans = n
}
func main(){
cm := NewcoffeeMachine()
cm.SetNumberOfCoffeeBeans(100)
}
// without pointers
type CoffeeMachine struct {
NumberOfCoffeeBeans int
}
func NewcoffeeMachine() CoffeeMachine {
return CoffeeMachine{}
}
func (cm CoffeeMachine) SetNumberOfCoffeeBeans(n int) CoffeeMachine {
cm.NumberOfCoffeeBeans = n
return cm
}
func main(){
cm := NewcoffeeMachine()
cm.SetNumberOfCoffeeBeans(100)
}
重點摘要
- 使用 pointers 效能沒有一定比較好
- 使用 pointers 可能會遇到物件在你不知道的狀況下被修改
- 可能會遇到 nil pointers 的問題
- 使用 values as parameters 可能會比較好
使用 pointers 時機
- 你確定要直接修改該物件時
- 當你需要 singleton
文章來源
Why You Should Avoid Pointers In Go