TheAlgorithms/Go · error
less func is necessary
Error message
less func is necessary
What it means
NewAny builds a generic Heap that delegates all element ordering to a caller-supplied less function. Because a nil lessFunc would cause a nil-function panic on the first comparison, the constructor validates it up front and returns this error.
Source
Thrown at structure/heap/heap.go:26
// Heap heap implementation using generic.
type Heap[T any] struct {
heaps []T
lessFunc func(a, b T) bool
}
// New gives a new heap object.
func New[T constraints.Ordered]() *Heap[T] {
less := func(a, b T) bool {
return a < b
}
h, _ := NewAny[T](less)
return h
}
// NewAny gives a new heap object. element can be anything, but must provide less function.
func NewAny[T any](less func(a, b T) bool) (*Heap[T], error) {
if less == nil {
return nil, errors.New("less func is necessary")
}
return &Heap[T]{
lessFunc: less,
}, nil
}
// Push pushes the element t onto the heap.
// The complexity is O(log n) where n = h.Len().
func (h *Heap[T]) Push(t T) {
h.heaps = append(h.heaps, t)
h.up(len(h.heaps) - 1)
}
// Top returns the minimum element (according to Less) from the heap.
// Top panics if the heap is empty.
func (h *Heap[T]) Top() T {
return h.heaps[0]
}View on GitHub (pinned to 5ba447ec5f)
Solutions
- Pass a valid func(a, b T) bool comparison to NewAny
- Check the error returned by NewAny before using the heap
- Provide a default comparator when the caller's is nil
Example fix
// before
h, _ := heap.NewAny[int](nil) // panics later on Push
// after
less := func(a, b int) bool { return a < b }
h, err := heap.NewAny[int](less)
if err != nil {
return err
} Defensive patterns
Strategy: validation
Validate before calling
if less == nil {
return errors.New("heap: comparator must not be nil")
}
h, err := heap.NewAny[T](less) Type guard
func hasComparator[T any](f func(a, b T) bool) bool { return f != nil } Try / catch
h, err := heap.NewAny[T](less)
if err != nil {
return nil, fmt.Errorf("heap init: %w", err)
} Prevention
- Always check the constructor's error before using the heap
- Provide a default comparator fallback in wrapper helpers
- Keep comparators next to heap construction so they are not dropped in refactors
When it happens
Trigger: Calling NewAny[T](nil), most often when the comparison function is stored in a variable that was never assigned, or when passing a method value that resolved to nil.
Common situations: Conditionally chosen comparators left nil on some code path; refactoring removed the closure but kept the call; generic helper functions that accept a func parameter which callers forget to supply.
Related errors
AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02).
Data as JSON: /api/errors/33868173260fe7e4.
Report an issue: GitHub.