Skip to content

Instantly share code, notes, and snippets.

@pastuhov
Created October 1, 2025 09:36
Show Gist options
  • Save pastuhov/cffa3dcb61590d23c875e8a6a337751f to your computer and use it in GitHub Desktop.
Save pastuhov/cffa3dcb61590d23c875e8a6a337751f to your computer and use it in GitHub Desktop.
package stack
// Stack is a LIFO collection.
//
// Concurrency: not safe for concurrent use.
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) {
var zero T
l := len(s.elements)
if l == 0 {
return zero, false
}
ret := s.elements[l-1]
s.elements[l-1] = zero
s.elements = s.elements[:l-1]
return ret, true
}
package stack_test
import (
"stack"
"testing"
)
func TestStack(t *testing.T) {
s := &stack.Stack[int]{}
s.Push(1)
s.Push(2)
s.Push(3)
if num, _ := s.Pop(); num != 3 {
t.Errorf("Expected 3, got: %v", num)
}
if num, _ := s.Pop(); num != 2 {
t.Errorf("Expected 2, got: %v", num)
}
if num, _ := s.Pop(); num != 1 {
t.Errorf("Expected 1, got: %v", num)
}
if _, ok := s.Pop(); ok == true {
t.Errorf("Expected false, got: %v", ok)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment