Go: Generics (alternatives and workarounds)

Go has some built-in generic data types, such as slices and maps, and generic functions, such as append and copy. However, there is no mechanism for writing your own generic functions.

Here are some techniques that can be used in place of parametric polymorphism in Go.

Find a well-fitting interface

Describe the generic behaviour of your data with an interface.

The io.Reader interface, which represents the read end of a stream of data, is a good example: - many functions take an io.Reader as input, - and many data types, including files, network connections, and ciphers, implement this interface.

Use multiple functions

If you only need to support a few data types, consider offering a seperate function for each type.

As an example, the two packages strings and bytes come with pretty much the same set of functions.

If this leads to an unmanageable amount of copy and paste, consider using a code generation tool, such as go generate.

Use the empty interface

If little is known about the data, consider using the empty interface interface{} in combination with type assertions and reflection. Libraries such as fmt and encoding/json couldn't have been written in any other way.

Write an experience report

If none of these solutions are effective, consider submitting an experience report:

This page collects experience reports about problems with Go that might inform our design of solutions to those problems. These reports should focus on the problems: they should not focus on and need not propose solutions.

We hope to use these experience reports to understand where people are having trouble writing Go, to help us prioritize future changes to the Go ecosystem. The Go Wiki: Experience Reports


Be the first to comment!