> I have some common code that I'd like to factor out into a utility function
> to reduce code duplication. I'm looping over chunked JSON responses from a
> server and am trying to aggregate the results in a arrays, for a number of
> different types.
You seem to want generic programming in Go, which is not available.
Attempts to emulate it will often result in weird code. Sometimes you
can achieve the same functionality while remaining idiomatic by
switching paradigms.
> The looping and aggregation code is identical for all of
> the types except for the type of the array in the map, so what I really want
> to end up with is a function signature:
>
> // functionally: accum = append(accum, objMap[key]...)
> func loopAndAggregate(key string, objMap interface{}, accum interface{})
>
>
> such that I can:
>
> func processFoos() []Foo {
> fooMap := make(map[string][]Foo)
> var foos []Foo
> loopAndAggregate("foos", fooMap, foos)
> return foos
> }
The example looks too simple to be interesting. Instead of repeating
for _, v := range fooMap { foos = append(foos, v...) }
you will be repeating
loopAndAggregate("foos", fooMap, foos)
which doesn't look like a saving, since it occupies roughly the same space.
Rémy.