Generic functions
A generic function is a function template that takes types as parameters. The generic function must compile for all possible type assignments of its arguments. The types a generic function can accept are described by “type constraints.” We will learn about these concepts in this section.
Writing a generic function that adds numbers
A good introductory example for illustrating generics is a function that adds numbers. These numbers can be various types of integers or floating-point numbers. Here, we will study several recipes with different capabilities.
How to do it...
A generic summation function that accepts int
and float64
numbers is as follows:
func Sum[T int | float64](values ...T) T { var result T for _, x := range values { result += x } return result }
The construct [T int | float64]
defines the type parameter for the Sum
function:
T
is the type name...