An introduction to generics in Golang

Click for: original source

The Go 1.18 release adds support for generics. Generics are the biggest change we’ve made to Go since the first open source release. By Robert Griesemer and Ian Lance Taylor.

In this article we’ll introduce the new language features. We won’t try to cover all the details, but we will hit all the important points. Generics are a way of writing code that is independent of the specific types being used. Functions and types may now be written to use any of a set of types.

Generics adds three new big things to the language:

  • Type parameters for function and types
  • Defining interface types as sets of types, including types that don’t have methods
  • Type inference, which permits omitting type arguments in many cases when calling a function

Functions and types are now permitted to have type parameters. A type parameter list looks like an ordinary parameter list, except that it uses square brackets instead of parentheses.

We can make a function generic - make it work for different types - by adding a type parameter list. In this example we add a type parameter list with a single type parameter T, and replace the uses of float64 with T.

import "golang.org/x/exp/constraints"

func GMin[T constraints.Ordered](x, y T) T {
    if x < y {
        return x
    }
    return y
}

Generics are a big new language feature in 1.18. These new language changes required a large amount of new code that has not had significant testing in production settings. That will only happen as more people write and use generic code. You will also find video of talk at GopherCon 2021 in the article. Good read!

[Read More]

Tags apis app-development cloud programming web-development golang