How to Use Generics with Methods in Go (And the Limitations)

Use type parameters in function signatures to create reusable, type-safe code in Go, noting constraints on instantiation and inference.

Use generics in Go methods by adding type parameters to the function signature with the func keyword, constrained by interface{} or specific type constraints.

func ToInt[P interface{ ~int }](p P) int { return int(p) }

Limitations include the inability to use generic methods on non-generic types without explicit instantiation, and the requirement that type parameters must be specified at the call site or inferred by the compiler.