Richard Bucker

Golang Generics or Generate

Posted at — Jun 25, 2020

I hate generics. I’m not sure how else to say it because it really does not add any real value and of course the conversation rages on. Frankly if you add generics and then all the other cruft that java programmers deem necessary then you end up with a go syntax that produces java. The JDK is already crossplatform-run-anywhere… so in the theme of scala why not create a golang that produces JDK capable code? Then you control the code… It’s how Microsoft came to C#!

Alternately you could create a code generator that produces or rather instantiates a generic as a template and produces the code…

my template

$ cat list_generic.tmpl 

//
// This is a {{.Type}}List
//

package {{Title .Type}}List

type {{Title .Type}}List {
        list []{{.Type}}
}

func New{{Title .Type}}List(n int) {{Title .Type}}List {
        x := {{Title .Type}}List{}
        x.list = make([]{{.Type}}, n)
        return x
}

func (x {{Title .Type}}List)Count() int {
        return len(x.list)
}

func (x {{Title .Type}}List)Append( item {{.Type}})  {
        x.list.append(item)
}

my string instance (StringList.go)

//go:generate gentmpl --output=StringList.go --type=string  list_generic.tmpl

my int instance (IntList.go)

//go:generate gentmpl --output=IntList.go --type=int  list_generic.tmpl

Now when I generate the files…

$ go generate IntList.go 
$ go generate StringList.go

I get a fully expanded template this this one:

// GENERATED by gentmpl; https://git/home/gentmpl, DO NOT EDIT
//go:generate gentmpl --output=IntList.go --type=int  list_generic.tmpl
//
// This is a intList
//

package IntList

type IntList {
        list []int
}

func NewIntList(n int) IntList {
        x := IntList{}
        x.list = make([]int, n)
        return x
}

func (x IntList)Count() int {
        return len(x.list)
}

func (x IntList)Append( item int)  {
        x.list.append(item)
}

gentmpl is a program I wrote for expanding templates with the expectation that I was generating go code. Since this was just a proof of concept it only implements the Title function in order to help with the types… This idea could be expanded as needed but at the end of the day it may still come down to adding objects, inheritance, and some kind of build-time reflection. None of which seem to add any real value.

Rather I would appreciate it someone would explain why golang needs generics versus using a language that has generics; like java.