Skip to content

Define Constraints and Generic Types

The Course
•
24 min study

any and cmp.Ordered are constraints someone else wrote. You can write your own, and you will need to when a function should accept a specific family of types. A constraint is an interface. Besides methods, an interface used as a constraint can list types, separated by |. A type parameter constrained by it may be any of those types, and the body may use the operations they all share.

The intermediate course used named types such as type TaskID int32. A named type is a different type from its underlying type, so int32 in a type list does not include TaskID. Writing ~int32 does: the tilde means "any type whose underlying type is int32".

Predict and run

Quantity allows any type whose underlying type is int or int32. Does total accept Minutes?

Predict, then run Go
package main

import (
	"fmt"
)

type Quantity interface {
	~int | ~int32
}

type Minutes int

func total[T Quantity](values []T) T {
	var sum T
	for _, v := range values {
		sum += v
	}
	return sum
}

func main() {
	fmt.Println(total([]int{3, 4}))
	fmt.Println(total([]Minutes{25, 35}))
	fmt.Println(total([]int32{7}))
}
Check your prediction
Text
7
60
7

+= is allowed because every type in the list supports it. The result keeps the caller's type: total([]Minutes{25, 35}) returns a Minutes, not an int. Remove the ~ from ~int and run again. The compiler stops with an error like this one, because Minutes is no longer in the set:

Text
Minutes does not satisfy Quantity (possibly missing ~ for int in Quantity)

A type with a type parameter

Types can have type parameters too. Stack[T] below is a stack of any element type. Its methods are declared on *Stack[T] and use T freely, but they do not list type parameters of their own: a method gets them from its type. A Stack[string] and a Stack[int] are different types, and Go checks every Push against the element type you chose.

A generic stack Go
package main

import (
	"fmt"
)

type Stack[T any] struct {
	items []T
}

func (s *Stack[T]) Push(v T) {
	s.items = append(s.items, v)
}

func (s *Stack[T]) Pop() (T, bool) {
	var zero T
	if len(s.items) == 0 {
		return zero, false
	}
	last := s.items[len(s.items)-1]
	s.items = s.items[:len(s.items)-1]
	return last, true
}

func main() {
	var undo Stack[string]
	undo.Push("stock tent 5")
	undo.Push("order A1 tent:2")
	fmt.Println(undo.Pop())
	fmt.Println(undo.Pop())
	fmt.Println(undo.Pop())
}
Text
order A1 tent:2 true
stock tent 5 true
 false

The zero value of Stack[string] is an empty stack ready to use, just as the intermediate queue's zero value was. The last line starts with a space because Pop returned the empty string before false.

The comparable constraint

Map keys must support ==. The built-in constraint comparable allows exactly the types that do: numbers, strings, booleans, pointers, and structs and arrays made only of comparable parts. Slices, maps and functions are not comparable. Any generic code that uses a type parameter as a map key, or compares two values with ==, needs comparable.

Start concrete

Write the function for one type first and get it right. Make it generic only when a second type actually needs it. The generic version is then a small, mechanical change, and you already have a working example to check it against.

Practice

Exercise

Your turn

Write a generic Set[T comparable] type backed by a map[T]bool. Give it Add(v T) and Has(v T) bool methods and a Len() int method. Make the zero value usable, so the map is created on the first Add. Add tent, drill and tent again. Then print, on one line, the length, whether lamp is in the set and whether tent is. Asking about one missing and one present item shows that Has doesn't give the same answer every time.

The output should be:

Text
2 false true
Your working space Go
package main

func main() {
	// Define Set[T comparable] and its methods, then use it.
}
Hint 1: the idea

Adding the same key to a map twice leaves one entry, so the set's length counts distinct values.

Hint 2: a first step

In Add, check if s.items == nil and create the map with make(map[T]bool) before writing to it. Reading from a nil map is fine, so Has needs no such check.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

type Set[T comparable] struct {
	items map[T]bool
}

func (s *Set[T]) Add(v T) {
	if s.items == nil {
		s.items = make(map[T]bool)
	}
	s.items[v] = true
}

func (s *Set[T]) Has(v T) bool {
	return s.items[v]
}

func (s *Set[T]) Len() int {
	return len(s.items)
}

func main() {
	var items Set[string]
	for _, name := range []string{"tent", "drill", "tent"} {
		items.Add(name)
	}
	fmt.Println(items.Len(), items.Has("lamp"), items.Has("tent"))
}
Text
2 false true

The repeated tent does not add a second entry, so the length is 2. Has on a missing key returns the map's zero value, false, with no extra lookup. Try Set[[]string]: the compiler rejects it, because slices are not comparable.

Was this article helpful?

Your response is saved on this device.