gointerfacegeneric-programming

Is there a way to generically represent a group of similar functions?


package main

import "fmt"

type Pet interface {
    Bark()
}

type Dog int

func (d Dog) Bark() {
    fmt.Println("W! W! W!")
}

type Cat int

func (c Cat) Bark() {
    fmt.Println("M! M! M!")
}

type AdoptFunc func(pet Pet)

func adoptDog(dog Dog) {
    fmt.Println("You live in my house from now on!")
}
func adoptCat(cat Cat) {
    fmt.Println("You live in my house from now on!")
}

func main() {
    var adoptFuncs map[string]AdoptFunc
    adoptFuncs["dog"] = adoptDog // cannot use adoptDog (type func(Dog)) as type AdoptFunc in assignment
    adoptFuncs["cat"] = adoptCat // the same as above
}

As the code above, is there a way to use a map or array to collect a bunch of similar functions adoptXxx? If not, what is right pattern to use for this situation?


Solution

  • To use the map as a function collection you'll have to change the signature of your functions to match. func(Pet) is not the same type as func(Dog).

    You can re-write AdoptXXX functions to take in Pet and do a type select to ensure correct pet is being input:

    func adoptDog(pet Pet) {
        if _, ok := pet.(Dog); !ok {
            // process incorrect pet type
        }
        fmt.Println("You live in my house from now on!")
    }