Generics in Go
Introduction
Generics in Go allow you to write flexible and reusable code. They enable you to define functions, data structures, and types that can work with any data type. This tutorial will guide you through the basic concepts and usage of generics in Go with detailed explanations and examples.
Basic Syntax
In Go, you define generics by using type parameters. Type parameters are specified in square brackets []
after the function name or type name.
func Print[T any](value T) { fmt.Println(value) }
In this example, T
is a type parameter. The any
keyword is used as a constraint indicating that T
can be any type.
Using Constraints
Constraints are used to restrict the types that can be substituted for a type parameter. Go provides a few built-in constraints, but you can also define your own.
type Number interface { int | int32 | int64 | float32 | float64 } func Add[T Number](a, b T) T { return a + b }
In this example, we define a Number
interface to constrain the type parameter T
to specific numeric types.
Generic Data Structures
You can also define generic data structures using type parameters.
type Stack[T any] struct { items []T } func (s *Stack[T]) Push(item T) { s.items = append(s.items, item) } func (s *Stack[T]) Pop() T { item := s.items[len(s.items)-1] s.items = s.items[:len(s.items)-1] return item }
In this example, we define a generic Stack
data structure that can store items of any type.
Instantiation and Usage
To use a generic function or data structure, you need to specify the type parameter when calling the function or creating an instance of the data structure.
func main() { Print(123) Print("Hello, generics!") var intStack Stack[int] intStack.Push(10) intStack.Push(20) fmt.Println(intStack.Pop()) var stringStack Stack[string] stringStack.Push("Go") stringStack.Push("Generics") fmt.Println(stringStack.Pop()) }
In this example, we instantiate the Stack
data structure with different types and use the Print
function with different data types.
Conclusion
Generics in Go provide a powerful way to write flexible and reusable code. By using type parameters and constraints, you can create functions and data structures that can work with any data type. This tutorial covered the basic syntax, usage of constraints, generic data structures, and instantiation with examples.