TheAlgorithms/Go · error
stack list is empty
Error message
stack list is empty
What it means
SList.Peek returns the value at the top of the linked-list-backed stack without popping it. When the stack is empty, it returns this error (and an empty-string placeholder) because there is no top element. It is a misuse guard: callers must check IsEmpty() first.
Source
Thrown at structure/stack/stacklinkedlistwithlist.go:33
)
// SList is our struct that point to stack with container/list.List library
type SList struct {
Stack *list.List
}
// Push add a value into our stack
func (sl *SList) Push(val any) {
sl.Stack.PushFront(val)
}
// Peak is return last value that insert into our stack
func (sl *SList) Peek() (any, error) {
if !sl.IsEmpty() {
element := sl.Stack.Front()
return element.Value, nil
}
return "", fmt.Errorf("stack list is empty")
}
// Pop is return last value that insert into our stack
// also it will remove it in our stack
func (sl *SList) Pop() (any, error) {
if !sl.IsEmpty() {
// get last element that insert into stack
element := sl.Stack.Front()
// remove element in stack
sl.Stack.Remove(element)
// return element value
return element.Value, nil
}
return "", fmt.Errorf("stack list is empty")
}
// Length return length of our stack
func (sl *SList) Length() int {View on GitHub (pinned to 5ba447ec5f)
Solutions
- Check sl.IsEmpty() before calling Peek().
- Handle the returned error and treat it as 'stack empty' rather than using the placeholder value.
- Ensure push operations actually execute before peek paths run (check control flow).
Example fix
// before
top, _ := sl.Peek()
compare(top)
// after
if sl.IsEmpty() {
return // nothing on the stack
}
top, err := sl.Peek()
if err != nil {
return err
}
compare(top) Defensive patterns
Strategy: validation
Validate before calling
if sl.IsEmpty() {
return errors.New("cannot peek: stack is empty")
}
top, err := sl.Peek() Type guard
func peekSafe(sl *stack.SList) (any, bool) {
if sl.IsEmpty() {
return nil, false
}
v, err := sl.Peek()
return v, err == nil
} Try / catch
top, err := sl.Peek()
if err != nil {
if strings.Contains(err.Error(), "empty") {
return // stack empty, handle accordingly
}
return err
} Prevention
- Always call IsEmpty() before Peek().
- Never use the empty-string return when err != nil.
- Verify pushes execute before peek paths in expression-evaluation code.
When it happens
Trigger: Calling Peek() on an empty SList — a newly created stack, one whose elements were all popped, or one never pushed to.
Common situations: Balanced-parentheses / expression-evaluation code that peeks before verifying the stack has operands, or peeking after a drain loop in undo-history implementations.
Related errors
- dequeue is empty we got an error
- error queue is empty
- failed to Encrypt
- failed to Decrypt
- no text to encrypt
AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02).
Data as JSON: /api/errors/e83c81a63133e719.
Report an issue: GitHub.