Skip to content

Instantly share code, notes, and snippets.

@eikaas
Created March 31, 2020 04:17
Show Gist options
  • Save eikaas/77656ae36a66bd1c367fe3f910909aa4 to your computer and use it in GitHub Desktop.
Save eikaas/77656ae36a66bd1c367fe3f910909aa4 to your computer and use it in GitHub Desktop.
package zek
import "sync"
// Stack is a simple stack for arbitrary types.
type Stack struct {
sync.Mutex
v []interface{}
}
// Len returns number of items on the stack.
func (s *Stack) Len() int {
s.Lock()
defer s.Unlock()
return len(s.v)
}
// Put item onto stack.
func (s *Stack) Put(item interface{}) {
s.Lock()
defer s.Unlock()
s.v = append(s.v, item)
}
// Peek returns the top element without removing it. Panic it stack is empty.
func (s *Stack) Peek() interface{} {
s.Lock()
defer s.Unlock()
if len(s.v) == 0 {
panic("peek at empty stack")
}
return s.v[len(s.v)-1]
}
// Pop item from stack. It's a panic if stack is empty.
func (s *Stack) Pop() interface{} {
s.Lock()
defer s.Unlock()
if len(s.v) == 0 {
panic("pop from empty stack")
}
last := len(s.v) - 1
v := s.v[last]
s.v = s.v[0:last]
return v
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment