Skip to main content
Generics in Go allow you to write code that works with different data types while maintaining type safety. Instead of creating separate functions for each type, you can define one function that operates on multiple types in a type-safe way.

Syntax

func FunctionName[T constraint](param T) ReturnType {
    //
}

Type Constraints

Go does not support direct union types. You cannot do something like:
type Number int | float64
Instead, you can use an interface to define a type set used as a generic constraint:
type Number interface {
    int | float64
}
The | operator is only valid in generic constraints. It specifies that a type parameter can be one of several types.Then use it like:
func add[T Number](a T, b T) T {
    return a + b
}
You can also use | directly without declaring a named interface:
func add[T int | float64](a T, b T) T {
    return a + b
}

Examples

Example 1: Basic Generic Function

func main() {
    fmt.Println(add(1, 2))     // 3
    fmt.Println(add(1.5, 2.3)) // 3.8
}

func add[T int | float64](a T, b T) T {
    return a + b
}
func main() {
    fmt.Println(addInts(1, 2))       // 3
    fmt.Println(addFloats(1.5, 2.3)) // 3.8
}

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

func addFloats(a, b float64) float64 {
    return a + b
}

Example 2: Multiple Type Parameters

func main() {
    fmt.Println(swap(2.5, 5))      // 5, 2.5
    fmt.Println(swap("Hello", 99)) // 99, Hello
}

func swap[T any, U any](a T, b U) (U, T) {
    return b, a
}

Example 3: Generic Structs

type gasEngine struct {
    hp int
}

type electricEngine struct {
    kWh int
}

type car[T gasEngine | electricEngine] struct {
    model  string
    year   int
    engine T
}

func main() {
    gCar := car[gasEngine]{
        model: "Audi",
        year:  2018,
        engine: gasEngine{
            hp: 385,
        },
    }

    eCar := car[electricEngine]{
        model: "Tesla",
        year:  2022,
        engine: electricEngine{
            kWh: 60,
        },
    }

    fmt.Println(gCar, eCar) // {Audi 2018 {385}} {Tesla 2022 {60}}
}

Build docs developers (and LLMs) love