Introduction of generic in Golang

2 min read Tweet this post

Generic programming is the practice of writing algorithms and data structures that work across a range of data types. In Go, generic programming has been a long-awaited feature that is currently being worked on by the community. In this article, we will explore the current state of generic programming in Go and discuss some of the benefits and drawbacks of the approach.

Generic programming is an approach to software development that aims to increase code reuse and reduce duplication. The idea is to write algorithms and data structures that work with a range of data types, rather than being limited to a specific type.

For example, consider the following function that adds two integers:

func add(a, b int) int {
    return a + b
}

This function only works with integers, and if we wanted to add floats, we would need to write a new function. With generic programming, we could write a single function that works with both integers and floats:


type Numeric interface {
    int64 | float64
}

func add[T Numeric](a, b T) T {
    return a + b
}

Here, the T is a type parameter that can be replaced with any type that satisfies the Numeric interface. This allows us to write a single function that works with multiple types.

Go currently does not have support for generic programming, but the community has been working on proposals to add the feature. One of the most promising proposals is the Go2 draft design, which introduces the concept of type parameters.

The Go2 draft design proposes a syntax for defining type parameters and constraints, as well as a way to instantiate generic functions and data structures. Here’s an example of how the add function could be written in Go2:

func add[T Numeric](a, b T) T {
    return a + b
}

This syntax defines a type parameter T that satisfies the Numeric interface. The add function can be called with any type that satisfies the Numeric interface.

There are several benefits of generic programming in Go:

  1. Code reuse: With generic programming, we can write algorithms and data structures that work with a range of data types, reducing code duplication and increasing code reuse.
  2. Simplicity: Generic programming can simplify code by reducing the number of functions and data structures required to work with different types.

There are also some drawbacks to generic programming in Go:

  1. Complexity: Generic programming can add complexity to code, especially if the syntax for defining type parameters and constraints is not simple and intuitive.
  2. Performance: Generic programming can also decrease performance if the generated code is not optimized for the specific types used at runtime.

Generic programming is a powerful technique that can simplify code and increase code reuse.

go practical generic