Start learning free

LESSON 38 OF 69 · OBJECT-ORIENTED PROGRAMMING

Base Keyword in Go: Calling the Embedded Parent

Practice Read the full explanation

TL ; DR:

Go has no classes or super. Puppy embeds a Dog, and when Puppy defines its own bark it hides the embedded one. The embedded Dog is still there as this.Dog, so this.Dog.bark() runs the parent's version. This lets you extend the parent's behavior instead of replacing it.


func (this Puppy) bark() {
    this.Dog.bark()   // do everything the parent did
    fmt.Printf("Yip! Said %s\n", this.name)
}

Why it matters

Overriding a method replaces the parent's behavior. Often you want to extend it instead: keep what the parent did and add something more. A typical example is a save method: the parent writes the row to the database, and a subclass runs the parent's save first and then writes a log line.

Your task

Dog (with its bark method), Puppy (which embeds Dog) and the constructor NewPuppy are written. You write the bark method of Puppy: func (this Puppy) bark(). Inside it:

  1. call the embedded parent's version with this.Dog.bark(), so Woof! I am <name> still prints;
  2. then fmt.Printf("Yip! Said %s\n", this.name).

Notes:

  • Puppy is declared as struct { Dog } (embedding). NewPuppy(name) builds it and is already written.
  • this.name works because the embedded Dog's fields are promoted to Puppy.

The driver (already written, it runs when you press Run):

buddy := NewPuppy("Buddy")
buddy.bark()
rex := NewPuppy("Rex")
rex.bark()
dog := Dog{name: "Max"}
dog.bark()
  • buddy is a Puppy: its bark prints the parent's line, then its own.
  • rex is another Puppy: the names come from the object, nothing is hard-coded.
  • dog is a plain Dog: its bark is unchanged and prints only the parent's line, with no Yip!.

Expected output:

Woof! I am Buddy
Yip! Said Buddy
Woof! I am Rex
Yip! Said Rex
Woof! I am Max
STEP 1 OF 3
    Ctrl + Enter to check

    GO · OBJECT-ORIENTED PROGRAMMING

    Base Keyword in Go, explained

    Problem overview

    Go has no classes, no inheritance and no super keyword. Code reuse comes from embedding: a struct lists another type as a field without a name, and the outer struct gains that type's fields and methods. In this lesson Puppy embeds Dog, and Dog has a method bark that prints Woof! I am <name>.

    The task is to give Puppy its own bark that does not throw the dog's behaviour away. It must first run the embedded Dog's bark, then print Yip! Said <name>. For a puppy named Buddy the output is two lines:

    Woof! I am Buddy
    Yip! Said Buddy
    

    A plain Dog named Max keeps its old behaviour and prints only Woof! I am Max.

    Approach: hide the method, then reach through to the embedded value

    When a struct embeds a type, the embedded type's methods are promoted: puppy.bark() works even if Puppy declares no bark, because the compiler turns it into puppy.Dog.bark(). If Puppy declares a method with the same name, that method wins for any call made on a Puppy. The embedded one is hidden, not deleted.

    The embedded value is a real field. Its name is the type's name, so a Puppy holds a field called Dog. Writing this.Dog.bark() names that field explicitly and runs the parent's version. That is the Go counterpart of "call the base method": replacing behaviour is just defining the method, and extending it is defining the method and calling this.Dog.bark() inside.

    The fields are promoted in the same way, which is why this.name works inside Puppy's method even though name is declared on Dog. this.Dog.name would mean the same thing.

    Step by step

    1. Declare the method with a Puppy receiver. func (this Puppy) bark() uses the same name as Dog's method, so calls on a Puppy reach it first. this is only a receiver name; Go programmers often use a short one like p, but the lesson uses this throughout. Close the body with } at once so the file always compiles.
    2. Call the parent first. this.Dog.bark() runs Dog's method on the embedded dog. Without this line, the puppy's version would replace the dog's and Woof! would never print.
    3. Add the puppy's own line. fmt.Printf prints Yip! Said followed by the name, then a newline. Putting it after the parent's call gives the order the lesson expects.

    The solution in Go

    type Dog struct {
        name string
    }
    
    func (this Dog) bark() {
        fmt.Printf("Woof! I am %s\n", this.name)
    }
    
    type Puppy struct {
        Dog
    }
    
    func NewPuppy(name string) Puppy {
        return Puppy{Dog: Dog{name: name}}
    }
    
    func (this Puppy) bark() {
        this.Dog.bark()
        fmt.Printf("Yip! Said %s\n", this.name)
    }
    
    
    
    func mainFunction() {
        buddy := NewPuppy("Buddy")
        buddy.bark()
        rex := NewPuppy("Rex")
        rex.bark()
        dog := Dog{name: "Max"}
        dog.bark()
    }
    

    Running the driver prints:

    Woof! I am Buddy
    Yip! Said Buddy
    Woof! I am Rex
    Yip! Said Rex
    Woof! I am Max
    

    The Go details worth knowing:

    • Embedding is composition, not subtyping. A Puppy is not a Dog for the type checker. A function that takes a Dog will not accept a Puppy; pass puppy.Dog instead. Interfaces are how Go lets different types be used interchangeably.
    • The composite literal names the embedded field. Puppy{Dog: Dog{name: name}} sets the field called Dog. You cannot write Puppy{name: name}, because promoted fields can't be used as keys in a composite literal.
    • There is no virtual dispatch. Inside Dog's methods the receiver is a Dog, so it never sees the puppy's override. If Dog had a method greet that calls d.bark(), then puppy.greet() would print only the dog's line, Woof! I am A, with no Yip!. Overriding in Go changes calls made on the outer type only.
    • Value receivers. this Puppy receives a copy. That is fine here because bark only reads. A method that must change the puppy needs a pointer receiver, (this *Puppy).
    • Go has no super. The embedded field's name takes its place, which also makes it clear which parent is meant when a struct embeds more than one type.

    Edge cases and common mistakes

    • Calling this.bark() inside Puppy's bark. That calls the same method again, which calls itself again, and so on until the program dies with fatal error: stack overflow. The parent's version needs the explicit this.Dog.bark().
    • Printing before calling the parent. The two lines come out in the wrong order and the lesson's tests, which compare the whole output, fail.
    • Dropping the parent call. The puppy then prints only Yip! Said Buddy. That is overriding, not extending.
    • Hard-coding a name. The driver builds two puppies, so the text has to come from this.name.
    • Expecting a plain Dog to change. Defining bark on Puppy does not touch Dog. Calling dog.bark() on a Dog still prints just the Woof! line.
    • Forgetting the import. The solution uses fmt; a file without import "fmt" doesn't compile. An import that nothing uses is also an error.

    Key takeaways

    • A method declared on the outer struct hides a promoted method of the same name.
    • The embedded value is reachable by its type's name, so this.Dog.bark() calls the parent's version.
    • Calling the parent first and then adding more output extends behaviour; leaving the call out replaces it.
    • Overrides apply only to calls on the outer type, because Go has no virtual dispatch through embedding.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free