Search code examples
gocomposition

Is this a valid implementation of composition in Go?


Is this valid composition? Or there are other solutions?

package main

import (
    "fmt"
    "strings"
)

type Person struct{ name string }

type Swimmer struct{}

func (s *Swimmer) Swim(name string) {
    fmt.Println(strings.Join([]string{
        name,
        " is swimming",
    }, ""))
}

type IronMan struct {
    person  Person
    swimmer Swimmer
}

func (i *IronMan) Swim() {
    i.swimmer.Swim(i.person.name)
}

func main() {
    ironMan := IronMan{
        person:  Person{"Mariottide"},
        swimmer: Swimmer{},
    }

    ironMan.Swim()
}

Solution

  • Go has struct embedding:

    package main
    
    import (
        "fmt"
    )
    
    type Person struct{ name string }
    
    func (p *Person) Talk(message string) {
        fmt.Printf("%s says: %s\n", p.name, message)
    }
    
    type Swimmer struct {
        Person
    }
    
    func (s *Swimmer) Swim() {
        fmt.Printf("%s is swimming\n", s.name)
    }
    
    type IronMan struct {
        Swimmer
    }
    
    func main() {
        ironMan := IronMan{Swimmer{Person{"Mariottide"}}}
    
        ironMan.Swim()
        ironMan.Talk("Hey")
    }