Embedding

Go structs may include others by listing their type name (alone) as a field. This brings in the fields of the class, and supports some of the features of class inheritance.

/* * Embedding */ package main import "fmt" import "math" /* * The Point yet again. */ type Point struct { x, y float64 } func (p *Point) to_s() string { return fmt.Sprintf("(%g,%g)", p.x, p.y) } func (from *Point) distance(to *Point) float64 { dx := from.x - to.x dy := from.y - to.y return math.Sqrt(dx*dx + dy*dy) } /* * Extending the point */ type NamedPoint struct { Point // This effectively inherits from Point. id string } func (p *NamedPoint) to_s() string { return p.id + ": " + p.Point.to_s() } func main() { // Go's approximation of inheritance does not hide the situation // from clients. np1 := NamedPoint{Point{3.0, 2.18}, "Frank"} np2 := NamedPoint{id: "Bill", Point: Point{2.81, -4.6}} fmt.Println("From", np1.to_s(), "to", np2.to_s(), "is", np1.distance(&np2.Point)) }