vendredi 1 novembre 2019

Golang promoted fields to composed struct

I was playing around with Go and ran into a problem relating to struct composition. Any advice and suggestions welcome (even if it's a 'this is against Go principles and a better alternative is X').

The scenario is that I have a generic struct that can has one method mapper.Each. Here is the code.

type m interface{
    Each(string, interface{})
}

type mapper struct{}

func (m mapper) Each(f func(string, interface{})) {
    var (
        i int
        n int
        v reflect.Value
        t reflect.Type
    )
    v = reflect.ValueOf(m)
    t = v.Type()
    n = v.NumField()
    for i = 0; i < n; i++ {
        var (
            key   = t.Field(i).Name
            value = v.Field(i).Interface()
        )
        f(key, value)
    }
}

As you can see, the method performs an iteration across all keys found in a struct and gets its value as an interface. The idea behind this structure is to allow any future struct to have a common method to get all key, values ignoring the type (assuming the struct satisfies an interface).

When I try and compose a new struct, such as type x struct{ mapper A string }, and call x.Each(...), there is no output. My guess is the definition of mapper.Each only supports taking care of its own properties, versus x being able to pass them back to mapper (so to speak).

What is the best mechanism to handle this case? Should all types like x perform a call to a generic function, such as getAllProperties or something.

Thanks for your thoughts and feedback.

Aucun commentaire:

Enregistrer un commentaire