Type parameters
A type parameter is a name in brackets on a function or type, such as T in func First[T any](s []T) (T, bool). Call sites substitute a real type, often inferred from the arguments.
Detailed Explanation
T in a generic function is not any at the call site. When you write First(users), T becomes User for that call. The compiler checks the body against the constraint, then checks the arguments against T. You get one piece of source and many checked instantiations.
Declaration. Type parameters follow the function name or type name: func First[T any](s []T) (T, bool). Multiple parameters are a list: [K comparable, V any]. Each parameter has a constraint. any is the constraint that allows every type. There is no omitted constraint.
Inference. Go infers type arguments from ordinary arguments, from other type arguments, and from assignment of the result. First(users) is enough when users is []User. Inference cannot see into an empty composite without a type: First([]int{}) works, First(nil) does not. Explicit arguments First[int](nil) fix that.
Identity. func f[T any](t T) instantiated as f[int] is a different function from f[string]. You can store f[int] in a var fn func(int). You cannot store a generic function value without instantiating it: var fn = First does not compile.
On types. type Pair[A, B any] struct { A A; B B } makes a family of structs. Field names and parameter names can match; the compiler can tell them apart. Methods must repeat the receiver's parameters: func (p Pair[A, B]) Swap() Pair[B, A]. You cannot add extra type parameters on the method.
Order and defaults. There are no default type arguments. If inference fails, the caller writes every type argument in order. Partial inference (writing only K and inferring V) is allowed when the rest can be seen from arguments.
What it costs. A type parameter is a compile-time name. It does not exist at runtime as a value you can range over. reflect still sees the concrete type after instantiation. The design cost is APIs that leak T into every caller when a concrete type would have been enough.
Code Examples
package main
import "fmt"
func First[T any](s []T) (T, bool) {
var zero T
if len(s) == 0 {
return zero, false
}
return s[0], true
}
func main() {
v, ok := First([]string{"a", "b"})
fmt.Println(v, ok)
}type Pair[A, B any] struct {
A A
B B
}
func (p Pair[A, B]) Swap() Pair[B, A] {
return Pair[B, A]{A: p.B, B: p.A}
}func explicit() {
v, ok := First[int](nil)
fmt.Println(v, ok) // 0 false
}Common Gotchas
An uninstantiated generic is not a value
you cannot put `First` in a map without `[T]`.
Methods cannot introduce new type parameters
only the receiver type's parameters are in scope.
`nil` does not infer `T`
write `First[int](nil)` or pass a typed slice.
The zero value of `T` is `var zero T`
there is no `T{}` unless `T` is constrained to a struct, which you usually do not want.