41 lines
578 B
Go
41 lines
578 B
Go
package common
|
|
|
|
import (
|
|
"errors"
|
|
"sync"
|
|
)
|
|
|
|
type Stack[T any] struct {
|
|
items []T
|
|
mutex sync.Mutex
|
|
}
|
|
|
|
func NewStack[T any]() *Stack[T] {
|
|
return &Stack[T]{
|
|
items: make([]T, 0),
|
|
mutex: sync.Mutex{},
|
|
}
|
|
}
|
|
|
|
func (s *Stack[T]) Push(item T) {
|
|
s.mutex.Lock()
|
|
defer s.mutex.Unlock()
|
|
|
|
s.items = append(s.items, item)
|
|
}
|
|
|
|
func (s *Stack[T]) Pop() (T, error) {
|
|
s.mutex.Lock()
|
|
defer s.mutex.Unlock()
|
|
|
|
if len(s.items) == 0 {
|
|
var empty T
|
|
return empty, errors.New("stack is empty")
|
|
}
|
|
|
|
item := s.items[len(s.items)-1]
|
|
s.items = s.items[:len(s.items)-1]
|
|
|
|
return item, nil
|
|
}
|