Skip to content

Latest commit

 

History

History
48 lines (37 loc) · 823 Bytes

3.2.1.md

File metadata and controls

48 lines (37 loc) · 823 Bytes

Go supports composition over inheritance.

package main

import "fmt"

type pet struct {
    name string
}

func (p pet) call() string {
    return fmt.Sprintf("Here %s", p.name)
}

type mammal struct {
    age int
    floofLevel int
}

func (m mammal) floof() string {
    switch {
    case m.floofLevel < 5:
        return "lil floof"
    default:
        return "total floofball"
    }
}

type dog struct {
    pet
    mammal
    sound string
}

func main() {
        d := dog{sound: "woof"}
        d.floofLevel = 10
        d.name = "todo"
        fmt.Printf("%s, you %s.\n", d.call(), d.floof())
}

Here we can see all the fields from mammal and pet have been promoted to the dog struct. Not only this, but you can also use the methods from mammal and pet on dog.


up -- back