Generics – The New Kid on the Block

Generics are a new feature in Go 1.18 that looks to have vast ramifications for Go's future. Generics provide a way to represent multiple types with a new feature called a type parameter to allow functions to operate on multiple types.

This differs from the standard interface{} where these types of operations always happen at runtime and where we must convert interface{} to the concrete type to do work.

Generics are a new feature, so we are only going to give a very general overview. The Go community and Go authors at this time do not have a set of best practices that have been rigorously tested. This comes with experience in using a feature, and we are only at the early stages of generics at this time, with more features around generics coming in the future.

Type parameters

Type parameters can be added to functions or struct types to support a generic type. However, a key gotcha is that they cannot be used on methods. This is the most requested feature; however, it poses certain challenges that the language authors are not sure how to deal with (or if they can be dealt with).

Type parameters are defined after the function name within brackets. Let's look at a basic one here:

Get hands-on with 1200+ tech skills courses.