Mahdi.Kh
September 21, 2026
In this part, we get familiar with generics and how to use them.
Support for generics was added to Go in version 1.18. Generics, or parametric polymorphism, is a feature that makes it possible to write functions and structures that can work with different data types, without us having to write separate code for each data type.
Before generics were introduced, if we needed a function that worked with different data types, we had to repeat the function's code several times, once for each data type.
For example, suppose you want a function that takes two numbers as input parameters and returns the larger of the two. We could have this function for the int and float64 types as follows:
In the example above, because each of our functions can't accept both the float64 and int types as its input or output parameter, we had to repeat an entirely identical piece of code twice.
To avoid this repetition in the earlier example, there are other solutions too:
Each of the approaches above has issues and isn't a clean solution. For example, if we use type assertion / interface assertion, our code will look like this:
The code above works correctly, but it has problems:
Using any reduces the program's readability: when using the max function, we first need to check its implementation to find out which data types it supports.
possible errors can't be caught at compile time. If we mistakenly call the function with a data type it doesn't implement, we'll run into a at runtime.
maxpanicint and float64 data types.Generics in Go are defined with the help of type parameters. That is, you can define a general type for a function and specify the actual type later, when it's used.
Using generics, we can rewrite the max function as follows:
In the example above, [int |float] is the list of argument types, and int and float are each considered an argument type. So the type T can be either float or int. The max function is considered a parametric, or generic, function.
When using the max function, we can control the type of the input and output parameters by specifying the type T. In the example below, we set the parameter T's type to int, so both of the function's input parameters must be of type int; otherwise, a compile-time error occurs.
Using a type parameter list, you can create generic types. Suppose we want to have a generic slice named List[T]; we can implement it as follows:
If a data type is generic (like List[T]), you can write methods that use its type parameters.
Unlike functions, methods can't have their own type parameter list, but they can use their data type's type parameter; for example, the code below runs into a compile-time error:
Previous part: Interfaces | Golang basics
Next part: Defer, Panic, and Recover | Golang basics