mardi 26 janvier 2021

Passing a struct method as an argument in Golang

I am not sure if I'm trying to exceed the limits of what Go will allow, but here is the context: I have type called Map with a hefty number of helpful member functions, such as Interpolate, Add, and Clear. I also have a struct type, Layered, that contains several Maps.

type Map [][]float64

func (m Map) Interpolate(min, max float64) { ... }
func (m Map) Add(val float64) { ... }
func (m Map) Clear() { ... }

type Layered struct {
    data []Map
}

I would like to add a member function to Layered that accepts any member function of Map as an argument, and then calls it on all of its contained Maps. Something along the lines of:

func (l Layered) MapCall(callMe func(Map)) {
    for _, m := range l.data {
        callMe(m)
    }
}

This partially works, but only for member functions of Map that take no additional arguments, such as Clear. Is it at all possible to accept any member function of Map as an argument (along with its potential parameters in the form of an ...interface{}), and then call the function, with its correct parameters, on all of the member Maps in a Layered? Something like this, for example:

func (l Layered) MapCall(callMe func(Map, ...interface{}), params ...interface{}) {
    for _, m := range l.data {
        callMe(m, params...)
    }
}




Aucun commentaire:

Enregistrer un commentaire