A Tour of Go - Generics Flashcards
What are generic functions in Go?
Go functions can be written to work on mulitple types using type parameters.
How is a generic function declared?
The type parameters of a function appear between brackets, before the function’s arguments.
func Index[T comparable](s []T, x T) int
This declaration means that s
is a slice of any type T
that fulfils the built-in constraint comparable
. x
is also a value of the same type.
What is the comparable
constraint?
comparable
is a useful constraint that makes it possible to use the ==
and !=
operators on values of the type.
Give an example of a generic function that compares a value to all slice elements until a match is found?
func Index[T comparable](s []T, x T) int { for i, v := range s { if v == x { return i } } return -1 }
What are generic types in Go?
A type can be parameterised with a type parameter, which could be useful for implementing generic data structures.
Give an example of a generic list type?
type List[T any] struct { next *List[T] val T }