gohugoio/hugo · error
strings: negative Repeat count
Error message
strings: negative Repeat count
What it means
Hugo's `strings.Repeat` wraps Go's `strings.Repeat`, which panics on a negative count. Hugo pre-checks the cast count and returns this error instead of panicking the whole build, matching the stdlib's error wording.
Source
Thrown at tpl/strings/strings.go:602
}
return strings.TrimSuffix(ss, sx), nil
}
// Repeat returns a new string consisting of n copies of the string s.
func (ns *Namespace) Repeat(n, s any) (string, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return "", err
}
sn, err := cast.ToIntE(n)
if err != nil {
return "", err
}
if sn < 0 {
return "", errors.New("strings: negative Repeat count")
}
return strings.Repeat(ss, sn), nil
}
View on GitHub ↗ (pinned to 8a468df065)
Solutions
- Clamp the count to zero before calling: `{{ $n := math.Max 0 (sub $width (len $s)) }}{{ strings.Repeat $n "-" }}`
- Fix the source data so the count is never negative
- Use a conditional to skip repeating when the count would be negative
Example fix
// before
{{ strings.Repeat (sub 10 (len .Title)) "." }}
// after
{{ $n := math.Max 0 (sub 10 (len .Title)) }}{{ strings.Repeat $n "." }} Defensive patterns
Strategy: validation
Validate before calling
{{ $n := int .count }}
{{ if ge $n 0 }}{{ strings.Repeat $n "-" }}{{ end }} Try / catch
{{ with try (strings.Repeat .count .s) }}{{ if .Err }}{{ warnf "negative repeat count %v" .count }}{{ else }}{{ .Value }}{{ end }}{{ end }} Prevention
- Clamp computed counts to zero: `math.Max 0 (sub $width (len $title))` — subtraction of lengths is the classic source of negatives.
- Validate user/config-supplied counts with `ge $n 0` before calling Repeat.
- Prefer `math.Max 0 ...` over conditional branches so the call site stays simple.
When it happens
Trigger: `{{ strings.Repeat -1 "ab" }}` or a computed count that goes negative, e.g. `{{ strings.Repeat (sub $width (len $s)) "-" }}` when the string is longer than the target width.
Common situations: Padding/alignment math in templates where the subtraction underflows for long titles; counts read from front matter that are negative or parsed oddly; porting code that assumed negative counts mean zero.
Related errors
- errKeyIsEmptyString
- %q is not a valid duration unit
- errMustTwoNumbersError
- uneven number of replacement pairs
- start argument must be integer
AI-assisted analysis of gohugoio/hugo@8a468df065 (2026-07-31).
Data as JSON: /data/errors/9f8a29c648b14096.json.
Report an issue: GitHub ↗.