方法的接收器 —— 物件接收器與指標接收器
物件接收器不會更新屬性
package tests import ( "fmt" "testing" ) type Consumer struct { Balance int64 } // 物件接收器 func (c Consumer) add(v int64) { c.Balance += v } func TestT1(t *testing.T) { c := Consumer{Balance: 10} // 不會改變... c.add(100) fmt.Println("c.Balance:>> ", c.Balance) // 10 }
指標接收器可以更新屬性
package tests import ( "fmt" "testing" ) type Consumer struct { Balance int64 } // 指標接收器 func (c *Consumer) add(v int64) { c.Balance += v } func TestT1(t *testing.T) { c := Consumer{Balance: 10} // 會改變... c.add(100) fmt.Println("c.Balance:>> ", c.Balance) // 110 }
123
123
123
123
123