GoLand
 
Get GoLand

How to use type parameters for generic programming

Last modified: 11 October 2024

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.