Type Parameters
Start with Type Parameters
A type parameter stands for a type whose permitted behavior is described by a constraint.
What you’ll learn
- Explain the main purpose of type parameters.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Type parameter names are conventional rather than magical: T, E, K and V are common. The declaration [K comparable, V any] allows K to be used as a map key while V can be any value type.
Different type parameters can represent different concrete types in one invocation. The compiler infers type arguments where possible; if inference is impossible, write them explicitly.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func entry[K comparable, V any](key K, value V) map[K]V {
return map[K]V{key: value}
}
func main() {
people := entry("age", 18)
fmt.Println("Age:", people["age"])
flags := entry(1, true)
fmt.Println("Flag:", flags[1])
}
Output
Age: 18
Flag: trueTrace what the program does
The first invocation infers K=string and V=int; the second infers K=int and V=bool. Both values are stored in correctly typed maps.
Avoid common mistakes
- A map key type must satisfy comparable.
- A type parameter describes an allowable set of types, not a runtime variable holding a type name.
Try it yourself
Create a generic swap function that returns the supplied pair in reverse order, using two type parameters.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Type Parameters in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.