The version you have written is correct and sane to understand. I wrote a benchmark:
package p
import (
"testing"
"strings"
)
var s = []string{"hello", "world", "this", "new", "world"}
func BenchmarkAcc1(b *testing.B) {
for n := 0; n < b.N; n++ {
Accumulate(s, strings.ToUpper)
}
}
func BenchmarkAcc2(b *testing.B) {
for n := 0; n < b.N; n++ {
Accumulate2(s, strings.ToUpper)
}
}
Here are a few results I got:
% go test -benchtime=10s -bench=.
testing: warning: no tests to run
PASS
BenchmarkAcc1 10000000 1510 ns/op
BenchmarkAcc2 10000000 1492 ns/op
ok _/home/satran/test 33.064s
As you can see there is no performance gain either, in fact your version works better.
Here is the source:
package p
func Accumulate(s []string, f func(st string) string) (result []string) {
for _, v := range s {
result = append(result, []string{f(v)}...)
}
return result
}
func Accumulate2(s []string, f func(st string) string) (result []string) {
for _, v := range s {
result = append(result, f(v))
}
return result
}