Our First Generic Function

Let’s learn how to use Go generics to write a simple and powerful function.

We'll cover the following

Generics are a feature that gives us the capability of not precisely specifying the data type of one or more function parameters, mainly because we want to make our functions as generic as possible. In other words, generics allow functions to process several data types without the need to write special code, as is the case with the empty interface or interfaces in general. However, when working with interfaces in Go, we have to write extra code to determine the data type of the interface variable we are working with, which is not the case with generics.

Let’s begin by presenting a small code example that implements a function that clearly shows a case where generics can be handy and save us from having to write lots of code:

Get hands-on with 1400+ tech skills courses.