Achieving type generic functions in Go, without using reflections

// No so useful.
func keys(m map[string]T) []string {
keys := make([]string, 0, len(m))
for key := range m {
keys = append(keys, key)
}
return keys
}
func keys(m interface{}) []string {
switch m := m.(type) {
case map[string]T:
keys := make([]string, 0, len(m))
for key := range m {
keys = append(keys, key)
}
return keys
default:
panic(fmt.Sprintf("unexpected type: %T", m))
}
}

Installation/How it works

go get github.com/motemen/go-typeswitch-gen/cmd/tsgen
# -w to rewrite the file, otherwise prints out to stdout
tsgen -w expand keys.go
func keys(m interface{}) []string {
switch m := m.(type) {
case map[string]int:
keys := make([]string, 0, len(m))
for key := range m {
keys = append(keys, key)
}
return keys
case map[string]bool:
keys := make([]string, 0, len(m))
for key := range m {
keys = append(keys, key)
}
return keys
case map[string]T:
keys := make([]string, 0, len(m))
for key := range m {
keys = append(keys, key)
}
return keys
default:
panic(fmt.Sprintf("unexpected type: %T", m))
}
}
go get github.com/motemen/go-typeswitch-gen/cmd/tsgen
tsgen expand $(go list -f '{{.Dir}}' github.com/motemen/go-typeswitch-gen)/_example/keys/keys.go

What will be a type placeholder?

type T1 interface{}
// +tsgen typevar
type NumT float64
var sum NumT
for _, x := range a {
sum = sum + x
}

TODO and Caveats

--

--

Web engineer at Kyoto, loves #Git #Golang #Vim

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store