Go

Custom Generic Constraints

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Type constraints are interfaces with type sets. Use them to express "any numeric" or "any ordered" without resorting to `any`.
Go
Raw
package main

import "fmt"

// Custom constraint — the type set of all numeric types
type Number interface {
    ~int | ~int8 | ~int16 | ~int32 | ~int64 |
        ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
        ~float32 | ~float64
}
// The ~ means "this type OR any type with the same underlying type"

func Sum[T Number](nums []T) T {
    var total T
    for _, n := range nums {
        total += n
    }
    return total
}

func Max[T Number](a, b T) T {
    if a > b { return a }
    return b
}

func main() {
    fmt.Println(Sum([]int{1, 2, 3, 4, 5}))                // 15
    fmt.Println(Sum([]float64{1.5, 2.5, 3.0}))            // 7
    fmt.Println(Max(3, 7))                                // 7
    fmt.Println(Max(3.14, 2.71))                          // 3.14
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.