Kothar Labs Contact Me

Generic Adapters in Go
Sun, 13 Aug 2017 / blog / go / generics

While playing about with ideas for generic types in Go, I have come up with what I'm calling a 'Generic Adapter'.

The approach I've taken here is essentialy that described by Kevin Gillette in a 2013 Post to golang-nuts. It implements 'erasure-style' generics by wrapping the generic implementation of each method with an adapter function which handles type assertions for the caller.

type Container struct {
    T SomeType

    Set func(value SomeType) SomeType
}

type Int64Container struct {
    T int64

    Set func(value int64) int64
}

func myProgram() {
    c := &Int64Container{}
    generic.Factory(Container{}).Create(c)
}

Source code implementing a proof of concept can be found on Bitbucket. I can't really say I recommend anyone using it, but it's satisfying to show that it works!

Comments | Read more...