Golang & Concurrency (50 Qs)•Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)
Generics in Go 1.18+: Type Constraints, Type Inference, and When to Avoid Generics.
senior LevelCode ExampleTypeScript
In Simple Words: Go 1.18 introduced generics via parameterized types and interfaces with type sets:
- Type Parameters:
[T any]or[T comparable]. - Custom Constraints: Using the approximation tilde operator (
~int) to match underlying custom types (type UserID int).
When to Avoid Generics:
Do not use generics when standard interfaces suffice. Use generics for pure data structures (Linked List, Queue, Heap) or utility functions operating uniformly on slices/maps (slices.Contains, maps.Keys).
go
// Generic Map function operating on any slice
func Map[T any, R any](items []T, fn func(T) R) []R {
result := make([]R, len(items))
for i, v := range items {
result[i] = fn(v)
}
return result
}