One of the key features in go is simplicity. As a result there are a number of utilities and data structures that are common in other high-level languages that do not come with the go stdlib.
One of them is a stack. Following is a very simple implementation of a stack that uses a slice to store the data.
The following is an implementation of a simple stack that takes any kind of pointer.
import "fmt"
type Stack[T any] struct {
stack []*T
}
func (s *Stack[T]) IsEmpty() bool {
return len(s.stack) == 0
}
func (s *Stack[T]) Push(q *T) {
// Add the new value to the end of the slice, which acts as the "top" of the Stack
s.stack = append(s.stack, q)
}
func (s *Stack[T]) Pop() *T {
if s.IsEmpty() {
return nil
} else {
// Get the index of the "top" of the Stack
idx := len(s.stack) - 1
// Retrieve the element from the stack that we are going to "pop" and return
retval := s.stack[idx]
// Remove it from the underlying slice by re-slicing the slice.
s.stack = s.stack[:idx]
return retval
}
}
func main() {
i := 1
j := 2
s1 := &Stack[int]{}
s1.Push(&i)
s1.Push(&j)
fmt.Printf("Pop! = %d\n", *s1.Pop())
fmt.Printf("Pop! = %d\n", *s1.Pop())
}