Skip to content

Instantly share code, notes, and snippets.

@ceving
Created November 5, 2023 21:58
Show Gist options
  • Save ceving/c7551382c3dd86a7bfd706ed74b50aae to your computer and use it in GitHub Desktop.
Save ceving/c7551382c3dd86a7bfd706ed74b50aae to your computer and use it in GitHub Desktop.
Go's embedding is no inheritance

In a language with inheritance the following code would print "Child". But in Go the following prints "Parent".

package main

import (
    "fmt"
)

type Hello interface {
    Hello()
}

type Parent struct{}

func (this Parent) Hello() {
    fmt.Printf("%T\n", this)
}

type Child struct {
    Parent
}

func main() {
    c := Child{}
    c.Hello()
}

In a language with inheritance, the child gets a copy of the parent's functionality: Each inherited method thinks of itself as a child. But in Go the child gets just a copy of the parent: Each embedded method continues to think of itself as a parent.

The syntactic suguar, which allows to call embedded methods with the child as a receiver is missleading. Although you call the method with the child as a receiver, the actual receiver of the method call is the copy of the parent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment