How do I implement a generic stack in Go?

In Go, you can implement a generic stack using interfaces and type assertions. A generic stack allows you to store elements of any type, making your data structure flexible and reusable. Below is an example of how to implement a simple generic stack in Go.

package main import ( "fmt" ) 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 } element := s.elements[len(s.elements)-1] s.elements = s.elements[:len(s.elements)-1] return element, true } func (s *Stack[T]) IsEmpty() bool { return len(s.elements) == 0 } func (s *Stack[T]) Size() int { return len(s.elements) } func main() { stack := Stack[int]{} stack.Push(1) stack.Push(2) stack.Push(3) fmt.Println(stack.Pop()) // Output: 3, true fmt.Println(stack.Pop()) // Output: 2, true fmt.Println(stack.Size()) // Output: 1 }

generic stack go stack implementation go generics go data structure