Programming Languages Go Subjective
Oct 04, 2025

What are generics in Go and how do they work?

Detailed Explanation
Generics in Go (Go 1.18+): • Type parameters for functions and types • Type constraints using interfaces • Compile-time type safety • Code reuse without interface{} Syntax: func Map[T, U any](slice []T, fn func(T) U) []U { result := make([]U, len(slice)) for i, v := range slice { result[i] = fn(v) } return result } Type constraints: type Ordered interface { ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64 | ~string } func Min[T Ordered](a, b T) T { if a < b { return a } return b } Generic types: type Stack[T any] struct { items []T } func (s *Stack[T]) Push(item T) { s.items = append(s.items, item) }
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback