> ## Content Index
> Fetch the complete content index at: https://sudosecurity.org/llms.txt
> Use this file to discover other available public pages before exploring further.

# Generics in Go, Explained
- URL: https://sudosecurity.org/understanding-generics-in-go-lang/
- Published: 2022-01-13T20:21:24.000Z
- Updated: 2026-11-17T17:08:11.000Z
- Description: The majority of programming languages have the concept of generic functions — code that can easily and efficiently accept one of a range of types without needing any specialization for each one – as long as those types all implement certain types of behaviors. Generics are a massive time-saver.…
- Author: Santhdium
- Tags: Programming, #coderoasis-archive, Go, Computer Science, Tutorials

Generic functions take a range of types without a separate implementation per type — write `sum` once, run it on every numeric type. Most languages had them for years before Go did.

## What Go had instead

Pre-1.18, the answer was `interface{}`: treat everything the same, check types at runtime. It worked, and it moved every mistake to production. The other workaround was duplication:

```go
func sumInt8(s []int8) int8 {
    var total int8
    for _, i := range s { total += i }
    return total
}
func sumInt64(s []int64) int64 {
    var total int64
    for _, i := range s { total += i }
    return total
}
// and float64, and...
```

## Type parameters on constraints

Go's generics parameterize a function over types bounded by an interface constraint:

```go
func sum[T ~int8 | ~int64 | ~float64](s []T) T {
    var total T
    for _, i := range s { total += i }
    return total
}

sum([]int64{1, 2, 3})   // T inferred as int64
```

The union `~int8 | ~int64 | ~float64` says what T may be; the `~` means "or any type with that underlying type" — so your custom `type Score int64` still matches. The compiler generates type-specific code at build time; old code keeps compiling untouched.

## Generic types too

```go
type Stack[T any] struct {
    items []T
}
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
func (s *Stack[T]) Pop() T {
    v := s.items[len(s.items)-1]
    s.items = s.items[:len(s.items)-1]
    return v
}
```

## When to bother

Collections and algorithms over multiple types: sums, maps, filters, containers. The signal is a duplicated body differing only in type. If you're not duplicating, generics are indirection for nothing — reach for them when the duplication shows up.