Golang Generics

From Adam Colton
Revision as of 05:08, 15 July 2017 by Adamcolton (talk | contribs) (Created page with "I am in the camp of those mostly opposed to generics. Maybe something innovative would convince me, but dropping in C++ style generics is something I strongly oppose. Let's s...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

I am in the camp of those mostly opposed to generics. Maybe something innovative would convince me, but dropping in C++ style generics is something I strongly oppose.

Let's start with two basic problems. First

 func Sum(vals []<T>)<T>{
   var sum <T>
   for _,v := range vals {
     sum += v
   }
   return sum
 }

What will that code do? What if I give it []string{"not","what","you","expect"}.

The next big problem is code explosion. If I include a line like

 var foo safemap<string, bloomfilter<string> >

how much code is that going to generate? Probably quite a bit.

Weak arguments

There are some arguments that don't hold any sway with me, lets get those out of the way.

Why do the language developers get generic and we don't

Because you'll abuse them, write unreadable code and then the rest of us have to clean up your mess.

Go works in practice because it's built on practice, not theory. It's a philosophically pure language. We get generics for slices and maps because that handles most of the cases we need. There isn't a generic bloomfilter because you don't need one very often and not everyone knows how they work.

I can't make a generic data structure

Yes you can, that's why we have interfaces. This is a matter of personal taste, but I've come around to liking interfaces more for this.

But I can't write a type safe generic data structure

Yes you can, take a non-type safe generic data structure and put a type safe wrapper around it. Yes, you will have to do it for each type, but if that really bothers you, you can write a code generator.

Good Arguments

Interfaces are slow

Yes, going through that pointer is a relatively expensive operation if you're doing a lot of simple ops on a lot of data. But I'm not convinced this problem justifies the inclusion of generics.

First, Go isn't **that** fast. It's fast enough for most things, but it doesn't have much in the way of optimization. If you're really worried about performance at that level, Go probably isn't the right language. And I don't think it's a good idea to fundamentally change the language to appeal to a small set of tasks the language will never be great at. At some point, I hope there will be an effort to improve the optimization and allow optimization flags that will trade compile time for run time. I think that opens the opportunity to treat interfaces like generics in some cases.

This is also another area where code generation can pick up some of the slack.