receiver参数类型对Go方法的影响 官网
值类型receiver不会改变原对象状态,因为是对象副本。指针类型receiver能改变原对象状态,因其是对象地址。 // 值类型 receiver 不改变原对象package mainimport "fmt"type Rectangle struct { Width int Height int}func (r Rectangle) DoubleSize() { r.Width *= 2 r.Height *= 2} // 运行结果:原对象宽高不变func main() { r := Rectangle{Width: 10, Height: 20} r.DoubleSize() fmt.Println(r.Width, r.Height)} 用指针类型时: // 指针类型 receiver 改变原对象package mainimport "fmt"type Rectangle struct { Width int Height int}func (r *Rectangle) DoubleSize() { r.Width *= 2 r.Height *= 2} // 运行结果:原对象宽高变为原来两倍func main() { r := &Rectangle{Width: 10, Height: 20} r.DoubleSize() fmt.Println(r.Width, r.Height)} 使用指针类型时要保证对象已初始化,不然会有运行时错误。