gohugoio/hugo · error
sequence length must be non-negative
Error message
sequence length must be non-negative
What it means
The `first` function rejects a negative limit after converting it to int: you cannot take the first -1 items of a sequence. (A limit larger than the list is fine — it's clamped to the list length — but negative is treated as a programming error.)
Source
Thrown at tpl/collections/collections.go:208
dict[key] = values[i+1]
}
return root, nil
}
// First returns the first limit items in list l.
func (ns *Namespace) First(limit any, l any) (any, error) {
if limit == nil || l == nil {
return nil, errors.New("both limit and seq must be provided")
}
limitv, err := cast.ToIntE(limit)
if err != nil {
return nil, err
}
if limitv < 0 {
return nil, errors.New("sequence length must be non-negative")
}
lv := reflect.ValueOf(l)
lv, isNil := hreflect.Indirect(lv)
if isNil {
return nil, errors.New("can't iterate over a nil value")
}
switch lv.Kind() {
case reflect.Array, reflect.Slice, reflect.String:
// okay
default:
return nil, errors.New("can't iterate over " + reflect.ValueOf(l).Type().String())
}
if limitv > lv.Len() {
limitv = lv.Len()
}View on GitHub ↗ (pinned to 8a468df065)
Solutions
- Clamp the computed limit: `{{ $n := math.Max 0 (sub $total $offset) }}{{ first $n .Pages }}`.
- For 'all items', skip `first` entirely and range the collection directly instead of passing -1.
- Trace where the negative value originates (config, front matter, arithmetic) and fix it at the source.
Example fix
<!-- before -->
{{ range first (sub 3 (len .Pages)) .Pages }}...{{ end }}
<!-- after -->
{{ range first (math.Max 0 (sub 3 (len .Pages))) .Pages }}...{{ end }} Defensive patterns
Strategy: validation
Validate before calling
{{ $n := sub (len .Pages) 3 }}
{{ if ge $n 0 }}{{ range seq $n }}...{{ end }}{{ end }} Prevention
- Clamp computed lengths before calling seq: `{{ $n := math.Max 0 $n }}`
- Be careful with subtraction producing negatives when a collection is smaller than expected
- Guard seq calls driven by user/front-matter values with an explicit `ge $n 0` check
When it happens
Trigger: `{{ first -1 .Pages }}` or a computed limit that goes negative, e.g. `{{ first (sub $shown $total) .Pages }}` when `$total > $shown`.
Common situations: Arithmetic on pagination or 'remaining items' counts underflowing below zero, config values set to -1 intending 'unlimited' (Hugo's `first` has no such convention), or subtracting an offset from a count without clamping.
Related errors
- symdiff: failed to convert value: %w
- arguments to symdiff must be slices or arrays
- errWrongArgStructure
- errKeyIsEmptyString
- complement needs at least two arguments
AI-assisted analysis of gohugoio/hugo@8a468df065 (2026-07-31).
Data as JSON: /data/errors/99de922e37331615.json.
Report an issue: GitHub ↗.