In Go 1.18, Go added support for generics. Generics allow you to write functions and data structures that work with different types without duplicating code.
In Go, functions and types normally work with specific types, such as int or string.
Before generics, you had two choices to support multiple types.
First, you could write multiple functions with different names, such as SumInts and SumFloats.
This approach creates duplicate code that is difficult to maintain.
Second, you could use the empty interface any (interface{}).
However, the empty interface removes compile-time type checks and requires type assertions at runtime.
Generics solve this problem by providing type safety while avoiding duplicate code.
You define a generic function by adding type parameters in square brackets [...] after the function name.
Here is an example of a generic function that returns a reversed slice:
func Reverse[T any](s []T) []T {
result := make([]T, len(s))
for i, v := range s {
result[len(s)-1-i] = v
}
return result
}
In this example, T is a type parameter.
You can think of T as a placeholder for a real type.
The any keyword inside the square brackets is a type constraint.
The constraint tells the compiler what types are permitted for T.
Here, any means T can be any type.
You can call a generic function by passing the actual type in square brackets. This actual type is called a type argument.
numbers := []int{1, 2, 3}
reversedNumbers := Reverse[int](numbers)
In most cases, the Go compiler can automatically detect the type from the function arguments. This feature is called type inference. With type inference, you do not need to write the type argument in square brackets.
words := []string{"apple", "banana"}
reversedWords := Reverse(words)
In this example, the compiler sees that words is a slice of strings, so it infers that T is string.
Every type parameter must have a constraint. A constraint specifies which types you can use as type arguments. A constraint also determines the operations you are allowed to perform on values of that type.
any constraintThe any constraint allows any type.
In Go, any is an alias for the empty interface interface{}.
Because any allows every type, the function can only perform operations that work on all Go types.
For example, if you have two any values, holding slices, they cannot be compared with == as slices cannot be compared using ==.
comparable constraintGo provides a built-in constraint called comparable.
The comparable constraint allows any type that supports the == and != operators.
Comparable types include booleans, numbers, strings, pointers, channels, and structs or arrays made of comparable types.
Here is an example of a function that checks whether a slice contains a specific item:
func Contains[T comparable](elems []T, target T) bool {
for _, elem := range elems {
if elem == target {
return true
}
}
return false
}
Because T uses the comparable constraint, using elem == target is valid.
If you replace comparable with any, the compiler will report an error.
Starting with Go 1.18, interfaces can define sets of types in addition to methods.
You can use the pipe character | to list the allowed types in an interface.
type Number interface {
int | int64 | float64
}
You can now use Number as a constraint for a function:
func Double[T Number](value T) T {
return value * 2
}
Because all types in Number support the * operator, Go allows value * 2 inside the function.
~
Sometimes you create a custom type definition based on a primitive type:
type MyInt int
The Number constraint defined above only permits the exact types int, int64, and float64.
If you pass a MyInt value to Double, the compiler produces an error because MyInt does not match int.
To allow any type whose underlying type is int, add a tilde ~ before the type:
type Number interface {
~int | ~int64 | ~float64
}
Now you can use Double with values of type MyInt.
cmp.Ordered constraintThe standard library provides the cmp.Ordered constraint in the cmp package.
The cmp.Ordered constraint allows any type that supports the comparison operators <, <=, >, and >=.
You can also use type parameters to define generic types, such as structs.
Here is an example of a generic Stack data structure:
type Stack[T any] struct {
elements []T
}
func (s *Stack[T]) Push(v T) {
s.elements = append(s.elements, v)
}
func (s *Stack[T]) Pop() (T, bool) {
if len(s.elements) == 0 {
var zero T
return zero, false
}
lastIndex := len(s.elements) - 1
top := s.elements[lastIndex]
s.elements = s.elements[:lastIndex]
return top, true
}
When you declare a variable of a generic type, you must provide the type argument in square brackets:
intStack := Stack[int]{}
intStack.Push(42)
stringStack := Stack[string]{}
stringStack.Push("hello")
Type inference only works for generic functions. You must always specify the type argument when creating values of a generic type.
Generics are a powerful feature, but you do not need to use them for every problem.
Use generics in situations like these:
Use interfaces instead in situations like these:
func Process(src io.Reader) over func Process[T](src T).For more information, see the Go Generics Tutorial, the Go Blog introduction to generics, and the Go Language Specification on Type Parameters.
You manage an exclusive movie theater. In order to attend a movie, people must purchase annual passes, then can attend movies for free.
Your theater maintains a log of admissions. You want to use that log to track which members used their annual pass this month. You also want to get information about age demographics of your customers. You realize you can use sets to solve these goals.
A set is a perfect data type to store this type of data.
A set is a data type used to store distinct, unique values in no particular order. Distinct and unique means an element is either in the set or not in the set; unlike with an array, it cannot be in the set multiple times. Sets are typically unordered; if you list the elements in a set, the order you get may be different from the order they were added -- or even different from the order you got on the prior list!
A fundamental property of sets is membership checks: the ability to check if a set contains an element. Membership checks are core to almost all uses of a set.
Go does not provide a built in set data type.
It is common to use a map[<type>]struct{} or map[<type>]bool in place of a set; similar to a set, a map allows adding distinct, unique elements and supports membership checks.
To track the attendance and age demographics, you want to use a set.
You don't want to write separate sets for names and ages; instead, you can use a generic set for both.
Define a Set type as a map[T comparable]struct{} to store attendees.
Write a NewSet[T comparable]() function that returns an empty Set[T].
names := NewSet[string]()
Now you're ready to record attendee information.
Write an Add[T]() method adds an element to the set.
names := NewSet[string]()
names.Add("Alice")
Now that you have a set of attendees, you can check if specific members and age demographics showed up.
Write a Contains[T](element) method that returns if a member or age demographic is in the Set.
names := NewSet[string]()
names.Add("Alice")
names.Contains("Alice")
// => true
names.Contains("Bob")
// => false
Another month has passed and you have a new Set of age demographics.
Your marketing manager wants to know if the new releases this month have changed what age demographics are showing up.
Write an Equals[T](other) method that determines if two Sets have the same elements.
agesOne := NewSet[int]()
names.Add(25)
agesTwo := NewSet[int]()
names.Add(25)
agesOne.Equals(agesTwo)
// => true
agesThree := NewSet[int]()
names.Add(35)
agesOne.Equals(agesThree)
// => false
Sign up to Exercism to learn and master Go with 36 concepts168 exercises, and real human mentoring, all for free.