134

Does anybody know why there is no real support for generics/templates/whatsInAName in Go? So there is a generic map, but that's supplied by the compiler, while a Go programmer can't write her own implementation. With all the talk about making Go as orthogonal as possible, why can I USE a generic type but not CREATE a new one?

Especially when it comes to functional programming, there are lambdas, even closures, but with a static type system lacking generics, how do I write, well, generic higher order functions like filter(predicate, list)? OK, Linked lists and the like can be done with interface{} sacrificing type safety.

It looks like generics will only be added to Go as an afterthought, if at all,. I do trust Ken Thompson to do way better than the Java implementers, but why keep generics out? Or are they planned and just not implemented yet?

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • I think it's worth pointing out: using interface{} does not sacrifice type safety. It is a type, and can be asserted (not cast) to other types, but these assertions still invoke runtime checks to maintain type safety. – cthom06 Oct 12 '10 at 11:41
  • 14
    `interface{}` sacrifices *static* type safety. However this is a somewhat strange complaint to make when mentioning Scheme is the next paragraph, since Scheme normally doesn't have static type checking. – poolie Nov 13 '10 at 07:37
  • @poolie: What I'm concerned with is sticking to ONE paradigm within a language. Either I'm using static type safety XOR not. –  Apr 27 '12 at 09:28
  • 2
    how about https://github.com/facebookgo/generics ? – Thellimist Jul 22 '15 at 03:43
  • So to keep you updated > A language proposal implementing a form of generic types has been > accepted for inclusion in the language. If all goes well it will be > available in the Go 1.18 release. Here is the [proposal](https://github.com/golang/go/issues/43651). – Henry Harutyunyan May 18 '21 at 04:33
  • I’m voting to close this question because there is generics in Go, now. – Inanc Gumus May 28 '22 at 09:46

5 Answers5

82

Note: Generics were added to Go in version 1.18.


You will find the answer here: http://golang.org/doc/faq#generics

Why does Go not have generic types?

Generics may well be added at some point. We don't feel an urgency for them, although we understand some programmers do.

Generics are convenient but they come at a cost in complexity in the type system and run-time. We haven't yet found a design that gives value proportionate to the complexity, although we continue to think about it. Meanwhile, Go's built-in maps and slices, plus the ability to use the empty interface to construct containers (with explicit unboxing) mean in many cases it is possible to write code that does what generics would enable, if less smoothly.

This remains an open issue.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Vinzenz
  • 2,749
  • 17
  • 23
  • As a Go beginner, I wonder what "the empty interface to construct containers" is? – amoebe Jul 07 '12 at 08:24
  • 14
    @amoebe, "the empty interface", spelled `interface{}`, is the most basic interface type, and every object provides it. If you make a container holding them, it can accept any (non-primitive) object. So it's very similar to a container holding `Objects` in Java. – poolie Jul 30 '12 at 07:55
  • @poolie Can you elaborate? For instance, who's "them" in "holding them"? – Flavius Jun 23 '13 at 08:30
  • "They" are "objects implementing `interface{}`". A Go `[]interface{}` is similar to a Java `Object[]`: an array each of whose slot contains any kind of object. A `map[string]interface{}` holds arbitrary objects indexed by a name. – poolie Jul 02 '13 at 04:18
  • 4
    @YinWang Generics are not that simple in a type inferred environment. More importantly; interface{} is not equivalent to void* pointers in C. Better analogies would be C#'s System.Object or Objective-C's id types. Type information is preserved and can be "cast" (asserted, actually) back to its concrete type. Get the gritty details here: http://golang.org/ref/spec#Type_assertions – tbone Aug 25 '13 at 20:50
  • 2
    @tbone C#'s System.Object (or Java's Object per se) is essentially what I meant by "C's void pointers" (ignoring the part that you can't do pointer arithmetic in those languages). Those are where the static type information gets lost. A cast will not help much because you will get a runtime error. – Ian Sep 04 '13 at 20:16
  • @Yin, there's a ton of discussion on go-nuts about generics. The problem for them is the hidden costs associated with boxing and unboxing by using a Java or C# like generics system. The problem with template expansion like C++ is the executable size and complexity it adds to the compiler, which right now is blazing fast because of the design decisions they've made. – Chris Pfohl Nov 02 '13 at 17:38
  • 1
    @ChristopherPfohl D's templates seem to have quite a bit less of compile time overhead, and normally you don't generate more code with templates than you would normally do otherwise (you could, in fact, end up with _less_ code depending on circumstances). – Cubic Jan 03 '14 at 17:46
  • @Cubic: don't get me wrong. I'm constantly wishing go had generics, I bump into things that would feel cleaner all the time. Have you *measured* the compile time overhead of templates in D? How do D templates differ from C++'s? – Chris Pfohl Jan 03 '14 at 19:45
  • 3
    @ChristopherPfohl I think only Java generics has boxing/unboxing issue for primitive types? C#'s reified generic doesn't have the issue. – ca9163d9 Jan 12 '14 at 02:50
37

A proposal for generics was implemented for the Go 1.18 release, which was released on 15 March 2022

"Go 2"

The generics design started under the umbrella of Go2, first at https://blog.golang.org/go2draft and there were several more draft specs over the next 3 years.

Go 1

Russ Cox, one of the Go veterans wrote a blog post entitled The Generic Dilemma, in which he asks

…do you want slow programmers, slow compilers and bloated binaries, or slow execution times?

Slow programmers being the result of no generics, slow compilers are caused by C++ like generics and slow execution times stem from the boxing-unboxing approach that Java uses.

The fourth possibility not mentioned in the blog is going the C# route. Generating the specialized code like in C++, but at runtime when it is needed. I really like it, but Go is very unlike C# so this is probably not applicable at all…

I should mention that using the popular Java 1.4 like technique of generic programming in go that casts to interface{} suffers from exactly the same problems as boxing-unboxing (because that's what we are doing), besides the loss of compile time type safety. For small types (like ints) Go optimizes the interface{} type so that a list of ints that were cast to interface{} occupies a contiguous area of memory and takes only twice as much space as normal ints. There is still the overhead of runtime checks while casting from interface{}, though. Reference.

All projects that add generic support to go (there is several of them and all are interesting) uniformly go the C++ route of compile time code generation.

TylerH
  • 20,799
  • 66
  • 75
  • 101
user7610
  • 25,267
  • 15
  • 124
  • 150
  • My solution of this dilemma would be for Go to default to "slow execution times" with the option to profile the program and recompile the most performance sensitive parts in a "slow compilers and bloated binaries" mode. Too bad that people actually implementing stuff like that tend to take the C++ route. – user7610 Nov 05 '15 at 13:48
  • 1
    It was mentioned that small types (i.e. int) that are stored in `[]interface{}` use 2x the RAM as `[]int`. While true, even smaller types (i.e. byte) use up to 16x the RAM as `[]byte`. – BMiner Sep 18 '18 at 23:55
  • There is actually no dilemma with the C++ approach. If a programmer chooses to write template code, the benefit of doing so must overwhelms the cost of slow compilation. Otherwise, he could just do it the old way. – John Z. Li Mar 21 '19 at 05:23
  • The dilemma is about which approach to chose. If you resolve the dilemma by going the C++ approach, the dilemma is resolved. – user7610 Mar 21 '19 at 12:32
4

To add to and update the excellent answers by @Vinzenz and @user7610.

Although it's far from certain, after over a decade of work it looks like a design for parametric polymorphism, what is colloquially but misleadingly called generics, is coming in the next year or two. It was a very hard problem to find a design that works within the existing language and feels as if it belongs, but Ian Taylor invested a phenomenal amount of energy into the problem and it looks like the answer is now in reach. See https://evrone.com/rob-pike-interview.

"Type Parameters - Draft Design" supports the use of type parameters where you can read functions that handle incoming parameters without depending on the type specified in the function declaration. See https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md.

For example, the PrintSlice function receives a slice of integers or strings and prints it. See https://www.jetbrains.com/help/go/how-to-use-type-parameters-for-generic-programming.html.

package main

import "fmt"

func PrintSlice(type T)(s []T) {
    for _, v := range s {

        fmt.Print(v)
    }
}

func main() {
    PrintSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9})
    PrintSlice([]string{"a", "b", "c", "d"})
}

You can test this example here https://go2goplay.golang.org/p/I09qwKNjxoq. This playground works just like the usual Go playground, but it supports generic code. See https://blog.golang.org/generics-next-step.

Parametric polymorphism basically means 'this function or data structure works identically with any type". That's what we also call generics. Eg the length of an array doesn't depend on what's in the array. See https://news.ycombinator.com/item?id=23560798.

The earliest that generics could be added to Go would be the Go 1.17 release, scheduled for August 2021. See https://blog.golang.org/generics-next-step.

2

Actually, according to this post:

Many people have concluded (incorrectly) that the Go team’s position is “Go will never have generics.” On the contrary, we understand the potential generics have, both to make Go far more flexible and powerful and to make Go far more complicated. If we are to add generics, we want to do it in a way that gets as much flexibility and power with as little added complexity as possible.

Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
0

Parametric polymorphism (generics) is under consideration for Go 2.

This approach would introduce the concept of a contract, that can be used to express constraints on type parameters:

contract Addable(a T) {
  a + a // Could be += also
}

Such a contract could then be used thusly:

func Sum(type T Addable)(l []T) (total T) {
  for _, e := range l {
    total += e
  }
  return total
}

This is a proposal at this stage.


Your filter(predicate, list) function could be implemented with a type parameter like this:

func Filter(type T)(f func(T) bool, l []T) (result []T) {
  for _, e := range l {
    if f(e) {
      result = append(result, e)
    }
  }
  return result
}

In this case, there is no need to constrain T.

P Varga
  • 19,174
  • 12
  • 70
  • 108
  • 4
    If you're reading this answer today, be aware that *contracts* have been dropped from the draft proposal: https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md#what-happened-to-contracts – jub0bs Jun 28 '20 at 19:53