Working with Generics
It happens often that you write a function that does some computation using values of a certain type (say, integers), but as the development progresses, you suddenly need to do the same thing but with another data type as well (say, float64
). So you copy/paste the first function and modify it to have a different name and data types. Perhaps the most obvious and well-known examples of this situation are container data types such as maps and sets. You build a container type for integer values, then you do the same for it using strings, then for a struct, and so on.
Generics is a way of doing this code copy/paste at compile time using code templates. First, you create a function template (generic function) or a data type template (generic type). You instantiate a generic function or type by providing types. The compiler takes care of instantiating the template with the types you provided, and checks if the instantiated generic type or function is compilable with...