...

/

Methods on Embedded Types

Methods on Embedded Types

This lesson covers in detail how to embed a functionality in a type and how methods work for embedded structs.

We'll cover the following...

When an anonymous type is embedded in a struct, the visible methods of that type are embedded as well. In effect, the outer type inherits the methods: methods associated with the anonymous field are promoted to become methods of the enclosing type. To subtype something, you put the parent type within the subtype. This mechanism offers a simple way to emulate some of the effects of subclassing and inheritance found in classic OO-languages; it is also very analogous to the mixins of Ruby.

Here is an illustrative example. Suppose we have an interface type Engine, and a struct type Car that contains an anonymous field of type Engine.

type Engine interface {
  Start()
  Stop()
}
type Car struct {
  Engine
}

We could then construct the following code:

func (c *Car) GoToWorkIn {
  // get in car
  c.Start();
  // drive to work
  c.Stop();
  // get out of car
}

The following complete example shows, how a method on an embedded struct can be called directly on a value of the embedding type.

Press + to interact
package main
import (
"fmt"
"math"
)
type Point struct {
x, y float64
}
func (p *Point) Abs() float64 {
return math.Sqrt(p.x*p.x + p.y*p.y)
}
type NamedPoint struct {
Point // anonymous field of Point type
name string
}
func main() {
n := &NamedPoint{Point{3, 4}, "Pythagoras"} // making pointer type variable
fmt.Println(n.Abs()) // prints 5
}

In the above code, at line 7, we make a struct of type Point with two fields x and y of type float64. We make another struct at line 15, of type NamedPoint with two fields in it. The first is an anonymous field of type Point and the second is name, a variable of type string. Look at the header of the method Abs() at line 11: func (p *Point) Abs() float64 . It shows that this method can only be called by the pointer to the variable of type Point, and it returns a value of type float64. Following is the formula for calculating the absolute value of a point:

v ...