在 Go 中,方法是带有 receiver(接收器)的函数,指示该方法属于哪个类型:
type User struct { Name string } func (u *User) SayHello() { fmt.Println("嗨,", u.Name) }
(u *User)) 的作用类似于函数中的第一个参数,但语法和调用方式不同。重要! 只能为您包中定义的类型声明方法(不允许对其他包中定义的类型(包括内置类型)声明方法)。关于别名(type alias)的行为是特殊的:
type MyInt int) 可以添加方法。type MyInt = int) 则无法添加方法,因为这只是一个别名。示例:
type MyInt int func (m MyInt) Double() int { return int(m) * 2 } // 类型别名 type MyIntAlias = int // func (m MyIntAlias) Double() int { ... } // 编译错误
可以为 []int 类型的切片或 type alias 声明方法吗?
回答: 对于内置类型的切片 ([]int) 不允许声明方法。对于基于切片的新用户定义类型可以:
type MySlice []int func (s MySlice) Sum() int { ... } // 允许
对于 type alias 则不可以:
type SuperSlice = []int // func (s SuperSlice) Sum() int { ... } // 错误
故事
故事
故事
尝试为外部包的类型(例如,time.Time)添加方法以标准化日期处理,但发现这在 Go 中是不可能的 — 只好使用组合和工具函数。