Sobes.tech
Senior

How to make a generic data structure in Go (working with any type of values)?

sobes.tech AI

Answer from AI

In Go version 1.18, generics were introduced, allowing the creation of data structures that work with any types.

To create a generic structure, you need to define a type with a type parameter, for example:

type Stack[T any] struct {
    elements []T
}

func (s *Stack[T]) Push(element T) {
    s.elements = append(s.elements, element)
}

func (s *Stack[T]) Pop() (T, bool) {
    if len(s.elements) == 0 {
        var zero T
        return zero, false
    }
    index := len(s.elements) - 1
    elem := s.elements[index]
    s.elements = s.elements[:index]
    return elem, true
}

Here, T is a type parameter, and any is a constraint meaning any type. Such a Stack structure can work with any data types, for example, Stack[int] or Stack[string].

Thus, generics in Go allow writing universal structures and functions parameterized by types.

How to make a generic data structure in Go (working… - sobes.tech