6.方法
Go没有类,用方法+类型代替传统类,实现封装,继承和多态。
// 定义自定义类型 Celsius(基于 float64)
type Celsius float64
// 给 Celsius 绑定 String() 方法(值接收者,仅读取)
func (c Celsius) String() string {
return fmt.Sprintf("%g°C", c)
}
// 给 Celsius 绑定 Set() 方法(指针接收者,修改原对象)
func (c *Celsius) Set(temp float64) {
*c = Celsius(temp)
}

浙公网安备 33010602011771号