Generic Functions
Start with Generic Functions
A generic function declares type parameters in square brackets before its ordinary parameters.
What you’ll learn
- Explain the main purpose of generic functions.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A function such as func repeat[T any](v T, n int) []T returns a slice whose element type matches the input. At a call site, type arguments can often be inferred from ordinary arguments, but explicit type arguments can be written as repeat[string]("x", 3).
Choose meaningful constraints when the body needs comparisons or arithmetic. The compiler rejects operations that the declared constraint does not support.
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 repeat[T any](value T, count int) []T {
result := make([]T, count)
for i := range result {
result[i] = value
}
return result
}
func main() {
fmt.Println(repeat("Go", 3))
fmt.Println(repeat[int](7, 2))
}
Output
[Go Go Go]
[7 7]Trace what the program does
The first call infers string; the second explicitly supplies int. A new slice of T values is allocated and filled, producing [Go Go Go] and [7 7].
Avoid common mistakes
- A negative count passed to make would panic; validate it in a reusable public API.
- Do not use a type parameter when a concrete function already meets the need cleanly.
Try it yourself
Add a generic pair function that returns two values of the same element type in a slice.
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 Generic Functions 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.