TheAlgorithms/Go · warning
empty slice provided
Error message
empty slice provided
What it means
ErrEmptySlice is the sentinel error returned by math functions (e.g. Mode) that require at least one element; Mode returns (0, ErrEmptySlice) when len(numbers) == 0. As a declared package-level error, callers can compare with errors.Is / equality.
Source
Thrown at math/mode.go:19
// mode.go
// author(s): [CalvinNJK] (https://github.com/CalvinNJK)
// time complexity: O(n)
// space complexity: O(n)
// description: Finding Mode Value In an Array
// see mode.go
package math
import (
"errors"
"github.com/TheAlgorithms/Go/constraints"
)
// ErrEmptySlice is the error returned by functions in math package when
// an empty slice is provided to it as argument when the function expects
// a non-empty slice.
var ErrEmptySlice = errors.New("empty slice provided")
func Mode[T constraints.Number](numbers []T) (T, error) {
countMap := make(map[T]int)
n := len(numbers)
if n == 0 {
return 0, ErrEmptySlice
}
for _, number := range numbers {
countMap[number]++
}
var mode T
count := 0
View on GitHub (pinned to 5ba447ec5f)
Solutions
- Check len(numbers) > 0 before calling Mode and handle the empty case explicitly.
- Use errors.Is(err, math.ErrEmptySlice) to detect it and return a domain-appropriate default.
- Fix upstream data loading so the slice is actually populated.
Example fix
// before
mode, err := math.Mode(values) // err = ErrEmptySlice
// after
if len(values) == 0 {
return 0, nil // or a domain default
}
mode, err := math.Mode(values) Defensive patterns
Strategy: validation
Validate before calling
if len(values) == 0 {
return 0, nil // define a default for the empty case
}
mode, err := math.Mode(values) Type guard
func nonEmpty[T any](xs []T) bool {
return len(xs) > 0
} Try / catch
mode, err := math.Mode(values)
if errors.Is(err, math.ErrEmptySlice) {
return 0, nil // or propagate a domain-specific empty result
}
if err != nil {
return 0, err
} Prevention
- Check slice length after every filter/map step before statistics calls.
- Treat empty inputs as a defined case in your API, not an afterthought.
- Compare with errors.Is against the exported sentinel, not string matching.
When it happens
Trigger: Calling math.Mode with an empty slice: Mode([]int{}) or Mode(someSlice) where the slice was never populated or was filtered down to zero elements.
Common situations: Reading an empty CSV/file into a slice; filtering that removes all items; a config list left empty; early-return paths where the caller forgot to check length before computing statistics.
Related errors
- integer overflow
- negative Exponent provided
- no Modular Inverse exists
- factorization failed
- ErrEmptyDequeue
AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02).
Data as JSON: /api/errors/96a22837307684fa.
Report an issue: GitHub.