GoLand
 
Get GoLand
You are viewing the documentation for an earlier version of GoLand.

How to use type parameters for generic programming

Last modified: 12 December 2022

By using type parameters, you can write functions that handle incoming parameters without depending on the type specified in the function declaration.

For example, the PrintSliceInts function receives a slice of integers and prints it.

To apply the same functionality to a slice of strings, you need to copy and paste the code of PrintSliceInts and make a new function called PrintSliceStrings, where everything is the same except for the signature.

You can rewrite the function and reuse your code. All you need is to introduce the type parameter and change the function parameter in the signature.