go-generics-stack
The implementation uses Go 1.26 generics with a slice-backed Stack[T any] type:
stack.go
package stack
// Stack is a generic LIFO data structure.
type Stack[T any] struct {
items []T
}
// New creates a new empty Stack.
func New[T any]() *Stack[T] {
return &Stack[T]{}
}
// Push adds an item to the top of the stack.
func (s *Stack[T]) Push(item T) {
s.items = append(s.items, item)
}
// Pop removes and returns the top item from the stack.
// Returns the zero value and false if the stack is empty.
func (s *Stack[T]) Pop() (T, bool) {
if s.IsEmpty() {
var zero T
return zero, false
}
idx := len(s.items) - 1
item := s.items[idx]
s.items = s.items[:idx]
return item, true
}
// Peek returns the top item without removing it.
// Returns the zero value and false if the stack is empty.
func (s *Stack[T]) Peek() (T, bool) {
if s.IsEmpty() {
var zero T
return zero, false
}
return s.items[len(s.items)-1], true
}
// IsEmpty returns true if the stack contains no items.
func (s *Stack[T]) IsEmpty() bool {
return len(s.items) == 0
}
Key design decisions:
- Pop and Peek use the comma-ok idiom (value, bool) — no panics on empty stacks.
- The zero value is returned when the stack is empty, which works for any type T.
- Slice backing keeps operations O(1) amortized.
All 9 tests pass, covering every method and all edge cases: | Test | What it verifies | |------|-----------------| | `TestNewStackIsEmpty` | A fresh stack is empty | | `TestPushAndPeek` | Push stores items; Peek returns top without removal | | `TestPop` | Pop removes and returns in LIFO order | | `TestPopOnEmptyStack` | Pop on empty returns `(zero, false)` | | `TestPeekOnEmptyStack` | Peek on empty returns `(zero, false)` | | `TestIsEmpty` | IsEmpty transitions correctly between pushes/pops | | `TestLIFOOrder` | 100-item push/pop cycle confirms full LIFO ordering | | `TestStringType` | Works with `string` (non-numeric type) | | `TestStructType` | Works with `struct` (custom type) | Race detection: `go test -race` — **PASS** (no races). ``` === RUN TestNewStackIsEmpty --- PASS: TestNewStackIsEmpty (0.00s) === RUN TestPushAndPeek --- PASS: TestPushAndPeek (0.00s) === RUN TestPop --- PASS: TestPop (0.00s) === RUN TestPopOnEmptyStack --- PASS: TestPopOnEmptyStack (0.00s) === RUN TestPeekOnEmptyStack --- PASS: TestPeekOnEmptyStack (0.00s) === RUN TestIsEmpty --- PASS: TestIsEmpty (0.00s) === RUN TestLIFOOrder --- PASS: TestLIFOOrder (0.00s) === RUN TestStringType --- PASS: TestStringType (0.00s) === RUN TestStructType --- PASS: TestStructType (0.00s) PASS ok stack 0.002s ``` ---
{"model": "gemini-2.5-flash", "problem_class": "go-generics-stack", "result": "passed", "tests": 9}