Home > Article > Backend Development > What are generics in Golang? Detailed analysis
Generics are features that allow function and type definitions to work for multiple types, thereby improving reusability and maintainability. Generics in Go use square brackets to represent type parameters and can accept various comparable types. Its use cases include eliminating duplicate code, improving readability, improving type safety, and more. A practical example of using generics is the Stack data structure, which supports multiple types of push and pop operations.
Generics are a programming language feature that allows the definition of functions, methods, and types that can work for multiple types. This significantly improves reusability and maintainability, eliminating the need for type reification code.
Generics were introduced in Go 1.18, bringing powerful features to the language. Generic type parameters are represented by square brackets as follows:
func Min[T comparable](a, b T) T { if a < b { return a } return b }
In this example, the Min
function can accept any comparable type, such as int, float64, or string.
Generics have many use cases in Go, including:
Let us consider a practical example of using generics. Suppose we have a Stack
data structure, which is a first-in-first-out (FIFO) collection. We want to be able to operate on various types of values:
package main type Stack[T any] struct { elements []T } func (s *Stack[T]) Push(item T) { s.elements = append(s.elements, item) } func (s *Stack[T]) Pop() T { item := s.elements[len(s.elements)-1] s.elements = s.elements[:len(s.elements)-1] return item } func main() { intStack := Stack[int]{} intStack.Push(1) intStack.Push(2) fmt.Println(intStack.Pop()) // 2 fmt.Println(intStack.Pop()) // 1 stringStack := Stack[string]{} stringStack.Push("Hello") stringStack.Push("World") fmt.Println(stringStack.Pop()) // World fmt.Println(stringStack.Pop()) // Hello }
This example creates a generic Stack data structure that can store any type of value. We created two stacks with int and string as value types and performed push and pop operations.
The above is the detailed content of What are generics in Golang? Detailed analysis. For more information, please follow other related articles on the PHP Chinese website!