Type Parameters
In this page:
Declaring Type Parameters
A generic function's type parameters are listed in square brackets right after the function name, each given a name and a constraint that limits which concrete types are allowed to be substituted in.
Example: Declaring Type Parameters
package main
import "fmt"
func Identity[T any](v T) T {
return v
}
func main() {
fmt.Println(Identity(42))
fmt.Println(Identity("hello"))
}
Login to try C/C++/Java/PHP code in the editor
Using Type Parameters in the Body
Once declared, a type parameter can be used anywhere a concrete type would go inside the function -- as the type of local variables, slice elements, or the return type.
Example: Using Type Parameters in the Body
package main
import "fmt"
func Duplicate[T any](v T) []T {
return []T{v, v}
}
func main() {
fmt.Println(Duplicate(7))
fmt.Println(Duplicate("go"))
}
Login to try C/C++/Java/PHP code in the editor
Type Inference at Call Sites
Go usually figures out the concrete type for a type parameter automatically from the arguments you pass, so most calls to a generic function look exactly like calling a normal one, without any extra bracket syntax.
Note: You only need to specify the type explicitly, e.g. Identity[int](5), when Go can't infer it from the arguments.
Example: Type Inference at Call Sites
package main
import "fmt"
func Pair[T any](a, b T) [2]T {
return [2]T{a, b}
}
func main() {
fmt.Println(Pair(1, 2)) // T inferred as int
fmt.Println(Pair("a", "b")) // T inferred as string
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting type parameters go in square brackets [T Constraint], not parentheses like regular parameters.
- Using a bare, unconstrained type parameter (any) and then trying to use operators like + on it, which only works for constrained types supporting that operator.
- Reusing the same type parameter name T across unrelated generic functions and assuming they share meaning -- each declaration is independent.
- A type parameter list appears in square brackets between a generic function's name and its regular parameters.
- Each type parameter has a constraint specifying which types are allowed, e.g. [T any] or [T int | float64].
- Type parameters can be used anywhere a type would normally appear: parameter types, return types, or local variables.
- Go usually infers type parameters from the arguments, so you rarely need to specify them explicitly at the call site.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: