Type Parameters

Type parameters are essentially variables that refer to specific types. They are defined in square brackets [] before the function arguments.

Syntax

func splitAnySlice[T any](s []T) ([]T, []T) {
    mid := len(s)/2
    return s[:mid], s[mid:]
}
  • T: The name of the type parameter (can be anything, but T is conventional).
  • any: The constraint. any is an alias for the empty interface interface{}, meaning the type can be anything.

Zero Values

To create a zero value for a generic type, you declare a variable of that type:

func getLast[T any](s []T) T {
    if len(s) == 0 {
        var zero T
        return zero // Returns 0 for ints, "" for strings, nil for pointers, etc.
    }
    return s[len(s)-1]
}

Naming Conventions

  • T: General Type.
  • K, V: Key and Value (common for maps).
  • S: Slice type.