Lesson 29 of 60 · Go
Generics – Type Parameters (Go 1.18+)
Duration: 25 minutes
Introducing Generics
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
Generics let you write reusable data structures without sacrificing type safety.
// A generic slice‑type that can hold any ordered type
func Index[T comparable](slice []T, value T) int {
for i, v := range slice {
if v == value { return i }
}
return -1
}
Constraints
type Number interface{ ~int | ~int64 | ~float64 }
func Sum[T Number](vals []T) T {
var total T
for _, v := range vals { total += v }
return total
}
Using generic types in structs
type List[T any] struct { items []T }
func (l *List[T]) Add(v T) { l.items = append(l.items, v) }