21 September 2022

Generics

The basics of Go generics.

Sidorenko Konstantin
Sidorenko Konstantin thecampagnards

The generics have finally arrived since the go 1.18. You will find here the basics on its use.

A very basic example that you will find a lot in your code. It’s the famous “Contains” in a slice that we recode each time:

package main

import "fmt"

func ContainsInt64(s []int64, v int64) bool {
	for _, t := range s {
		if t == v {
			return true
		}
	}
	return false
}

func ContainsFloat64(s []float64, v float64) bool {
	for _, t := range s {
		if t == v {
			return true
		}
	}
	return false
}

type Number interface {
	int64 | float64
}

// generics houra !!!
func Contains[V Number](s []V, v V) bool {
	for _, t := range s {
		if t == v {
			return true
		}
	}
	return false
}

// or
func Contains[V comparable](s []V, v any) bool {
	for _, t := range s {
		if t == v {
			return true
		}
	}
	return false
}

func main() {
	fmt.Println(ContainsInt64([]int64{1, 2, 3}, 1))
	fmt.Println(ContainsFloat64([]float64{1, 2, 3}, 1))

	fmt.Println(Contains([]int64{1, 2, 3}, 1))
	fmt.Println(Contains([]float64{1, 2, 3}, 1))
}

Go playground: https://go.dev/play/p/xeUh3GPI3Ok.

Another example with a function to online some pointers, that works with multiple types:

package main

import "fmt"

func ToPtr[V any](v V) *V {
	return &v
}

func main() {
	fmt.Println(ToPtr("a"))
	fmt.Println(ToPtr(1))
}

Go playground: https://go.dev/play/p/qcQB1oyCLgg.

Thanks to these generics you will find new libraries like https://pkg.go.dev/golang.org/x/exp/slices that will help you a lot.

In the slices library, you will find many functions that you used to code yourself, which are now available as generics and as a library:

package main

import (
	"fmt"

	"golang.org/x/exp/slices"
)

func main() {
	fmt.Println(slices.Contains([]int64{1, 2, 3}, 1))
	fmt.Println(slices.Contains([]float64{1, 2, 3}, 1))
}

Go playground: https://go.dev/play/p/CsnGdu_EC8Z.

You will find functions like:

  • Contains
  • Compare
  • Index
  • Sort

And more !

References

https://go.dev/doc/tutorial/generics

Categories

Golang Development