方法
值接收者 vs 指针接收者、方法集、不能给内置类型添加方法
方法
Go 的方法 = 带**接收者(Receiver)**的函数。接收者可以是值类型或指针类型——选择影响深远。
学完本章你将: 掌握值接收者 vs 指针接收者、方法集、不能给内置类型加方法。
方法定义
go
package main
import "fmt"
type Rectangle struct {
Width, Height float64
}
// 值接收者——操作的是副本
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// 指针接收者——可以修改原值
func (r *Rectangle) Scale(factor float64) {
r.Width *= factor
r.Height *= factor
}
func main() {
rect := Rectangle{10, 5}
fmt.Println(rect.Area()) // 50
rect.Scale(2) // Go 自动取地址
fmt.Println(rect.Area()) // 200
}
值 vs 指针接收者 —— 选择指南
go
// ✅ 指针接收者:需要修改接收者、接收者是大型 struct、保持一致性
func (r *Rectangle) SetWidth(w float64) { r.Width = w }
// ✅ 值接收者:不需要修改、接收者是小类型且不可变
func (r Rectangle) Area() float64 { return r.Width * r.Height }
💡 经验法则: 如果 struct 的任何方法用了指针接收者,全部方法都用指针接收者——保持一致性。
方法值 vs 方法表达式
go
// 方法值
f := rect.Area // 绑定到 rect
fmt.Println(f()) // 50
// 方法表达式
g := Rectangle.Area // 不绑定,需要传接收者
fmt.Println(g(rect)) // 50