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
- Declare the method with a
Puppyreceiver.func (this Puppy) bark()uses the same name asDog's method, so calls on aPuppyreach it first.thisis only a receiver name; Go programmers often use a short one likep, but the lesson usesthisthroughout. Close the body with}at once so the file always compiles. - Call the parent first.
this.Dog.bark()runsDog's method on the embedded dog. Without this line, the puppy's version would replace the dog's andWoof!would never print. - Add the puppy's own line.
fmt.PrintfprintsYip! Saidfollowed 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
Puppyis not aDogfor the type checker. A function that takes aDogwill not accept aPuppy; passpuppy.Doginstead. 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 calledDog. You cannot writePuppy{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 aDog, so it never sees the puppy's override. IfDoghad a methodgreetthat callsd.bark(), thenpuppy.greet()would print only the dog's line,Woof! I am A, with noYip!. Overriding in Go changes calls made on the outer type only. - Value receivers.
this Puppyreceives a copy. That is fine here becausebarkonly 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()insidePuppy'sbark. That calls the same method again, which calls itself again, and so on until the program dies withfatal error: stack overflow. The parent's version needs the explicitthis.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
Dogto change. DefiningbarkonPuppydoes not touchDog. Callingdog.bark()on aDogstill prints just theWoof!line. - Forgetting the import. The solution uses
fmt; a file withoutimport "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.
