Ramblings of an aging IT geek
← Ramblings of an aging IT geek
golang

generics in go, and whether i actually wanted them

After a few months with Go 1.18 generics I reach for them far less than I expected, and that is mostly a good thing.

Go source on a screen

Generics landed in 1.18 back in March, and I went in braced for the urge to rewrite half my code. That urge never really arrived. A few months on, I reach for type parameters maybe twice in a project, and both times it is the same shape: a tiny container or a Map/Filter helper I was previously copy-pasting per type.

The honest version is that most of my Go code is glue. It moves a struct from an HTTP handler to a database and back. There is nothing generic about that. interface{} was never the pain point people on Reddit promised me it was, because I almost never used it.

Where they do earn their keep is the boring plumbing nobody enjoys writing twice:

func Keys[K comparable, V any](m map[K]V) []K {
	out := make([]K, 0, len(m))
	for k := range m {
		out = append(out, k)
	}
	return out
}

That is it. That is the whole win for me so far. I deleted three near-identical keys functions and felt mildly smug.

The trap is the same as every language that grows generics: you can now express clever things, and cleverness reads worse at 2am than a bit of duplication does. So I am treating type parameters like sharp tools. Lovely when the job calls for one, and best left in the drawer the rest of the time.