← Back to Go Course | Chapter 12: Generics | Lesson 2 of 6

Type Parameters

A type parameter is a placeholder for 'whatever type you give me', written in square brackets, that the function fills in with a real type each time it's used.

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

markup
package main

import "fmt"

func Identity[T any](v T) T {
	return v
}

func main() {
	fmt.Println(Identity(42))
	fmt.Println(Identity("hello"))
}

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

markup
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"))
}

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

markup
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
}
Common Mistakes
  1. Forgetting type parameters go in square brackets [T Constraint], not parentheses like regular parameters.
  2. 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.
  3. Reusing the same type parameter name T across unrelated generic functions and assuming they share meaning -- each declaration is independent.
Chapter Summary
  • 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.