他の言語における継承にあたるものです。
他で定義したtypeを中に取り込んで、新たなtypeを定義することができます。
type Vertex struct {
x, y int
}
type Vertex3D struct {
Vertex // 継承
z int
}
func NewVertex3D(x, y, z int) *Vertex3D {
return &Vertex3D{Vertex{x, y}, z} // type定義の際、「Vertex」と記載したため、型の定義に合わせる必要がある。
}
func (v *Vertex3D) Scale(i int) {
v.x *= i
v.y *= i
v.z *= i
}
func (v *Vertex3D) Volume int {
return v.x * v.y* v.z
}
func main() {
v := NewVertex3D(2, 4, 7)
v.Scale(3)
fmt.Println(v.Volume()) // 1512
}
こんな形の継承も可能です。
type Int int
type VertexInt struct {
Vertex
Int
}
func NewVI(x, y, a int) *VertexInt {
return &VertexInt{Vertex{x, y}, Int(a)}
}
func main() {
a := NewVI(4, 5, 6)
fmt.Println(*a) // {{4 5} 6}
}