Konubinix' opinionated web of thoughts

Embedding Interfaces in Structs in Golang

Fleeting

not immediately clear what embedding an interface in a struct means

https://eli.thegreenplace.net/2020/embedding-in-go-part-3-interfaces-in-structs/

This allows to have a struct that has a default implementation of the functions of the interface that redirect to an aggregated implementation of the interface given when constructing the object.

package main

import "fmt"

type Fooer interface {
    Foo()
}

type Container struct {
    Fooer
}

// TheRealFoo is a type that implements the Fooer interface.
type TheRealFoo struct {
}

func (trf *TheRealFoo) Foo() {
    fmt.Println("real foo")
}
func main() {
    co := &Container{Fooer: &TheRealFoo{}}
    co.Foo()
}

Be careful, the name of the interface cannot be the name of the function, because it is embedded in the struct. Luckily, we are used to append -er to the interface.

This code is not valid

package main

import "fmt"

type Foo interface {
    Foo()
}

type Container struct {
    Foo
}

// TheRealFoo is a type that implements the Foo interface.
type TheRealFoo struct {
}

func (trf *TheRealFoo) Foo() {
    fmt.Println("real foo")
}
func main() {
    co := &Container{Foo: &TheRealFoo{}}
    co.Foo()
}