~/Golang Generic Functions Overview

Sep 15, 2025


Golang added generics support in version 1.18, allowing functions and types to handle types in a flexible and type-safe manner. This article reviews key details of implementing and using generic functions in Golang.

Generic Functions Syntax

Golang generic functions use type parameters defined in square brackets after the function name. The syntax is:

1
2
3
func FunctionName[T any](param T) T {
    // Function body
}

In this example, T is a type parameter constrained by the any constraint, which allows any type.

Constraints

Generic type parameters can be restricted using interfaces, such as:

1
2
3
4
5
6
func Min[T comparable](a, b T) T {
    if a < b {
        return a
    }
    return b
}

The comparable constraint ensures types can be compared with == and !=.

Instantiating Generic Functions

Generics are instantiated automatically when you call the function with concrete types. For example:

1
result := Min[int](5, 8)

Here, Golang infers [T] as int. Explicit type parameters are optional when the types can be inferred.

Multiple Type Parameters

Functions can declare more than one type parameter:

1
2
3
func Pair[A, B any](a A, b B) (A, B) {
    return a, b
}

See specification for parameter lists.

Type Sets and Custom Constraints

Constraints can be defined with custom interfaces with type sets:

1
2
3
type Adder[T any] interface {
    Add(b T) T
}

Then used as a constraint:

1
2
3
func AddAll[T Adder[T]](a, b T) T {
    return a.Add(b)
}

Limitations

Not all operations are allowed on generic types. Arithmetic or ordering requires explicit constraints or interfaces.

Type inference only works when parameter types are known from the arguments. See detailed examples in the generics proposal.

Common Use Cases

  1. Sorting with generic comparison
  2. Containers holding any type
  3. Generic utilities

Example: Generic Map Function

1
2
3
4
5
6
7
func Map[S any, T any](s []S, fn func(S) T) []T {
    result := make([]T, len(s))
    for i, v := range s {
        result[i] = fn(v)
    }
    return result
}

Detailed explanation at Go generics tutorial.

Testing Generics

Testing generic functions is identical to regular ones. Use table-driven tests.

Package Import Compatibility

Generics are only available in Go 1.18 or later. Ensure your build system uses an up-to-date Go toolchain.

Performance

Generics in Go are monomorphized at compile time, so there is minimal runtime overhead compared with interface-based solutions.

Conclusion

Golang generic functions improve code reusability and maintainability. Study the official generic design draft and real-world usage in the Go standard library for advanced techniques.

Tags: [golang] [generics] [functions] [programming]