12

Generics (alternatives and workarounds)

 3 years ago
source link: https://yourbasic.org/golang/generics/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Generics (alternatives and workarounds)

yourbasic.org/golang
bland-face.png

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

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 separate 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.

Use the empty interface

If little is known about the data, consider using the empty interface interface{} in combination with type assertions, and possibly also 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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK