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.

Get hands-on with 1200+ tech skills courses.