Start learning free

LESSON 631 OF 671 · OBJECT-ORIENTED PROGRAMMING

Inheritance in Go

Lesson

TL ; DR:

A child struct can embed a parent struct — it gets all the parent's fields and methods for free, and can add its own. This lets you reuse code instead of copy-pasting it.


type Puppy struct {
    Dog
}

func (p Puppy) whine() {
    fmt.Println("whimper")
}


Full lesson:

Inheritance is one of the four classic OOP pillars (along with encapsulation, polymorphism, and abstraction). The idea is simple: most real-world things are kinds of other things — a Puppy is a Dog, a Car is a Vehicle, a Manager is an Employee. When you model that "is-a" relationship in code, the child gets the parent's data and behavior automatically. Go has no classes or extends; it gets the same reuse by embedding one struct inside another.

What gets inherited?

  • Fields — the Puppy has a name field even though we only declared it on Dog.
  • Methods — the Puppy can call bark() even though we only defined it on Dog.
  • The contract — any interface that Dog's methods satisfy is satisfied by a Puppy too (we'll see this when we cover polymorphism). Unlike in class-based languages, you cannot pass a Puppy where a plain Dog value is expected.

What you still write

  • The constructor function (NewPuppy) has to build the embedded Dog too, because the parent's fields need initializing: Puppy{Dog: Dog{name: name}}.
  • Any new methods or new fields specific to the child.

Your task

Below the Dog struct, create a Puppy struct that embeds Dog and adds one new method, whine(), that prints "whimper". The harness creates a Puppy named "Buddy", calls its inherited bark(), and then its new whine().

Expected output:

Woof! I am Buddy
whimper
STEP 1 OF 8
    Ctrl + Enter to check