TheAlgorithms/Go · error
size must be greater than 0
Error message
size must be greater than 0
What it means
NewCircularQueue allocates a fixed-size ring buffer; it refuses to construct a queue with a non-positive capacity since a zero or negative capacity cannot store any items and would break the modulo arithmetic of the ring. The library returns this error instead of panicking on make([]T, size).
Source
Thrown at structure/circularqueue/circularqueuearray.go:31
// errors package: Provides functions to create and manipulate error values
import (
"errors"
)
// CircularQueue represents a circular queue data structure.
type CircularQueue[T any] struct {
items []T
front int
rear int
size int
}
// NewCircularQueue creates a new CircularQueue with the given size.
// Returns an error if the size is less than or equal to 0.
func NewCircularQueue[T any](size int) (*CircularQueue[T], error) {
if size <= 0 {
return nil, errors.New("size must be greater than 0")
}
return &CircularQueue[T]{
items: make([]T, size),
front: -1,
rear: -1,
size: size,
}, nil
}
// Enqueue adds an item to the rear of the queue.
// Returns an error if the queue is full.
func (cq *CircularQueue[T]) Enqueue(item T) error {
if cq.IsFull() {
return errors.New("queue is full")
}
if cq.IsEmpty() {
cq.front = 0
}View on GitHub (pinned to 5ba447ec5f)
Solutions
- Ensure the size argument is a positive integer before calling NewCircularQueue
- Add an explicit check or clamp: if size <= 0 { size = defaultSize }
- Fix the source of the size value (config, env var, flag) to supply a valid positive number
Example fix
// before
q, err := NewCircularQueue[int](cfg.QueueSize) // cfg.QueueSize == 0
// after
size := cfg.QueueSize
if size <= 0 {
size = 16 // sensible default
}
q, err := NewCircularQueue[int](size) Defensive patterns
Strategy: validation
Validate before calling
func validQueueSize(size int) bool { return size > 0 }
if !validQueueSize(n) { return fmt.Errorf("invalid queue size %d", n) } Try / catch
q, err := NewCircularQueue[T](n)
if err != nil {
return fmt.Errorf("queue init: %w", err)
} Prevention
- Never pass raw config/flag values as size without checking > 0
- Default to a positive constant when the size source is missing or zero
- Centralize queue construction in one helper that clamps the size
When it happens
Trigger: Calling NewCircularQueue[T](0) or NewCircularQueue[T](n) with n < 0, typically when the size comes from an unvalidated config value, user input, or a computed expression that evaluated to zero.
Common situations: Config file with missing or zero capacity field; computing size from a slice length that was empty; default struct values in Go (int zero value) passed straight through without initialization.
Related errors
AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02).
Data as JSON: /api/errors/d64558f0e60e4afe.
Report an issue: GitHub.