Implementing a stack using a slice
A surprisingly common use of a slice is to implement a stack. Here is how it is done.
How to do it...
A stack push is simply append
:
// A generic stack of type T type Stack[T any] []T func (s *Stack[T]) Push(val T) { *s = append(*s, val) }
To implement pop
, truncate the slice:
func (s *Stack[T]) Pop() (val T) { val = (*s)[len(*s)-1] *s = (*s)[:len(*s)-1] return }
Again, note the use of parentheses and indirections. We cannot write *s[len(*s)-1]
, because that is interpreted as *(s[len(*s)-1]
. To prevent that, we have (*s)
.