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
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?