Start learning free

LESSON 603 OF 639 · OBJECT-ORIENTED PROGRAMMING

Composition in Go in Go

Lesson

TL ; DR:

A struct can keep an object of another struct in a field. It passes work on to that object. A Car has an Engine. This is composition.


type Car struct {
    engine Engine   // a Car has an Engine
}

func (this Car) start() {
    this.engine.start()   // the Car asks its Engine
}


Full lesson:

Things are often made of other things. A car has an engine. A phone has a battery.

Code works the same way. One struct keeps an object of another struct in a field. This is called composition.

The outer object passes some work on to its part. Car's start just calls the engine's start. This is called delegation.

Has-a or is-a?

In Inheritance, Puppy embedded Dog. Embedding gives the outer struct all the methods of the inner one. That is Go's "is a": a Puppy is a Dog. A Car is not an Engine, so Car doesn't embed it. A field with a name, engine Engine, passes on no methods. Car chooses what to pass on.

Why it helps

  • The engine stays private. Code outside talks to the car, never to the engine.
  • Each struct does one job. Engine knows how to start. Car knows its name and how to drive.
  • A part can be replaced. A car with a new engine is still the same car.

The field is lowercase, so it is unexported, as in Access Modifiers. NewCar builds the engine with NewEngine().


Your task

The Engine struct is ready. Car already has a name and a drive method.

Give the Car struct an engine field. Build the engine in NewCar.

Then write Car's start method. It calls the engine's start.

The program makes a car named "Rocket". It starts the car, then drives it.

Expected output:

Engine started
Rocket is driving
STEP 1 OF 3
    Ctrl + Enter to check

    Composition in Go

    Keep going with Go500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free