方法的接收器 —— 对象接收器与指针接收器
对象接收器不会更新属性
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
标签:接收器,函数,fmt,testing,123,Go,新手,Balance,Consumer From: https://www.cnblogs.com/paulwhw/p/18301102