Understanding Go Generics: Concepts, History, and Practical Examples
This article introduces Go's newly added generic support, explains its concepts, historical development, usage examples, constraints, and best practices, while providing code snippets for functions, slices, maps, queues, and pointers, helping developers grasp how to write type‑safe reusable code in Go.
Go 1.17 introduced an experimental version of generics, paving the way for the full generic implementation in Go 1.18. Generics allow developers to write type‑parameterized functions and types, reducing code duplication and improving type safety.
The core syntax uses square brackets to declare type parameters, optionally constrained by interfaces. For example, a generic addition function can be written as:
func Add[T any](a, b T) T { return a + b }Constraints can be expressed with interfaces that list permissible operations or type sets. The standard library now provides a constraints package with common constraints such as Ordered , Signed , and Unsigned .
type Ordered interface { type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, float32, float64, string }Practical examples include:
Generic slice printing:
func printSlice[T any](s []T) { for _, v := range s { fmt.Printf("%v ", v) } fmt.Println() }Generic map transformation:
func mapFunc[T any, M any](a []T, f func(T) M) []M { n := make([]M, len(a)); for i, e := range a { n[i] = f(e) }; return n }Generic queue implementation:
type queue[T any] []T
func (q *queue[T]) enqueue(v T) { *q = append(*q, v) }
func (q *queue[T]) dequeue() (T, bool) { if len(*q) == 0 { var zero T; return zero, false }; r := (*q)[0]; *q = (*q)[1:]; return r, true }Generic pointer helper:
func pointerOf[T any](v T) *T { return &v }The article also discusses the evolution of generics in Go, the "generic dilemma" concerning trade‑offs between compile time, runtime performance, and programmer convenience, and provides guidance on when to use generics versus concrete types.
High Availability Architecture
Official account for High Availability Architecture.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.