Go generics work by defining type parameters in square brackets after a function or type name, allowing the compiler to generate specialized code for each concrete type used. The compiler substitutes the actual types at compile time, ensuring type safety without runtime overhead.
func ToInt[P interface{ ~int }](p P) int { return int(p) }
var IntID = ToInt[int](42)
In this example, P is a type parameter constrained to types underlying int. When ToInt[int] is called, the compiler generates a specific version of the function for int.