Go语言编程快速入门:组合和转发
P24 go23 - 组合和转发
组合
- 在面向对象的世界中,对象由更小的对象组合而成
- 术语:对象组合
- Go通过结构体实现组合(composition)
- Go提供了 embedding 特性,它可以实现方法的转发 forwarding
组合结构体(天气预报report)
- location
- temperature
- sol
- celsius
组合结构体的效果
type sol float64
type celsius int32
type location struct {
lat, lng float64
}
type temperature struct {
low, high celsius
}
type report struct {
sol sol
location location
temperature temperature
}
rp1 := report{
sol: 15.4,
location: location{lat: 20.1, lng: 100.0},
temperature: temperature{low: -1, high: 100},
}
方法的 embed
- 如果多个嵌入的结构体有同名的函数
- 则不能直接用嵌入方式来调用了
package main
import "fmt"
type celsius float64
type location struct {
lat, lng float64
}
type temperature struct {
low, high celsius
}
type report struct {
sol int
location
temperature
}
func (t temperature) average() celsius {
return (t.high + t.low) / 2
}
func main() {
rp1 := report{
sol: 15,
location: location{lat: 20.1, lng: 100.0},
temperature: temperature{low: -1.0, high: 100.0},
}
fmt.Printf("%+v \n", rp1.average())
fmt.Printf("%+v", rp1)
}
参考