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)
}

posted @ 2026-03-23 14:57  cyusouyiku  阅读(12)  评论(0)    收藏  举报