Built-in Generics

Currently (Go 1.11), Go doesn't support user-defined generic types, and only supports generics for first-level citizen composite types. We can use composite types to create infinite custom types by using all kinds of first-level citizen types in Go.

This article will show type composition examples and explain how to read these composited types.

Type Composition Examples

Type compositions in Go are designed very intuitive and easy to interpret. It is hardly to get lost in understanding Go composite types, even if for some very complex ones. The following will list several type composition examples, from simpler ones to more complex ones.

Let's view an simple composite type literal.
[3][4]int

When interpreting a composite type, we should look at it from left to right. The [3] on the left in the above type literal indicates that this type is an array type. The whole right part following the [4]int is another array type, which is the element type of the first array type. The element type of the element type (an array type) of the first array type is built-in type int. The first array type can be viewed as a two-dimensional array type.

An example on using this two-dimensional array type.
package main

import (
	"fmt"
)

func main() {
	matrix := [3][4]int{
		{1, 0, 0, 1},
		{0, 1, 0, 1},
		{0, 0, 1, 1},
	}

	matrix[1][1] = 3
	a := matrix[1] // type of a is [4]int
	fmt.Println(a) // [0 3 0 1]
}

Similarly,

Let's view another type.
chan *[16]byte

The chan keyword at the left most indicates this type is a channel type. The whole right part *[16]byte, which is a pointer type, denotes the element type of this channel type. The base type of the pointer type is [16]byte, which is an array type. The element type of the array type is byte.

An example on using this channel type.
package main

import (
	"fmt"
	"time"
	"crypto/rand"
)

func main() {
	c := make(chan *[16]byte)

	go func() {
		// Use double arrays to avoid data racing.
		var dataA, dataB = new([16]byte), new([16]byte)
		for {
			_, err := rand.Read(dataA[:])
			if err != nil {
				close(c)
			} else {
				c <- dataA
				dataA, dataB = dataB, dataA
			}
		}
	}()

	for data := range c {
		fmt.Println((*data)[:])
		time.Sleep(time.Second / 2)
	}
}

Similarly, type map[string][]func(int) int is a map type. The key type of this map type is string. The remaining right part []func(int) int denotes the element type of the map type. The [] indicates the element type is a slice type, whose element type is a function type func(int) int.

An example on using the just explained map type.
package main

import "fmt"

func main() {
	plusone := func(x int) int {return x + 1}
	square := func(x int) int {return x * x}
	double := func(x int) int {return x + x}

	transforms := map[string][]func(int) int {
		"increase,increase,increase": {plusone, plusone, plusone},
		"square,increase,double": {square, plusone, double},
		"double,square,square": {double, double, square},
	}

	for _, n := range []int{2, 3, 5, 7} {
		fmt.Println(">>>", n)
		for name, transfers := range transforms {
			result := n
			for _, xfer := range transfers {
				result = xfer(result)
			}
			fmt.Printf("   %v: %v \n", name, result)
		}
	}
}

Below is a type which looks some complex.
[]map[struct {
	a int
	b struct {
		x string
		y bool
	}
}]interface {
	Build([]byte, struct{a int; b struct {x string; y bool}}) error
	Update(dt float64)
	Destroy()
}

Let's read it from left to right. The starting [] at the left most indicates this type is a slice type. The following map keyword shows the element type of the slice type is a map type. The struct type denoted by the struct literal enclosed in the [] following the map keyword is the key type of the map type. The element type of the map type is an interface type which specifies three methods. The key type, a struct type, has two fields, one field a is of int type, and the other field b is of another struct type struct {x string; y bool}.

Please note that the second struct type is also used as one parameter type of one method specified by the just mentioned interface type.

To get a better readability, we often decompose such a type into multiple type declarations. The type alias T declared in the following code and the just explained type above denote the identical type.
type B = struct {
	x string
	y bool
}

type K = struct {
	a int
	b B
}

type E = interface {
	Build([]byte, K) error
	Update(dt float64)
	Destroy()
}

type T = []map[K]E

The Current Status Of The Built-in Generic Functionalities In Go

Besides the built-in generics for composite types, there are several built-in functions also support generics. Such as the built-in len function can be used to get the length of values of arrays, slices, maps, strings and channels. Generally, the functions in the unsafe standard package are also viewed as built-in functions.

The fact that currently Go doesn't support generics for custom types and functions really brings some inconveniences in Go programming sometimes. For example, the types of the arguments and results of most functions in the math standard package are float64. When we want to use these functions on values of other kinds of numeric types, we must first convert the values to float64 values as arguments, and we must convert the float64 results back to the original numeric types, which is not only inconvenient, but also is not efficient.

Luckily, many kinds of Go projects don't need custom general types and functions. And the shortcomings caused by lacking of custom generics can be partically remedied by the reflection functionalities provided in Go (at run time) and code generating (at compile time).

The Future Of Generics In Go

Go language design and development team wouldn't mind supporting generics feature in Go, it is just that they haven't found a generics solution which will keep Go simple and clean yet. So, it is (very) possible that Go 2 will support custom generics. Currently, there is a page for Go 2 draft designs, including a generics design draft. The draft is still in the early phase so the final implementation would be much different.


The Go 101 project is hosted on both Github and Gitlab. Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.

Support Go 101 by playing Tapir's games. Cryptocurrency donations are also welcome:
Bitcoin: 1xucQbv5jujFPPwhyg395ri5yV71hx9g9
Ethereum: 0x5dc4aa2c2bbfaadae373dadcfca11b3358912212