gohugoio/hugo · error

cannot index slice/array with nil

Error message

cannot index slice/array with nil

What it means

Thrown by the Index/doIndex function when indexing a slice, array, or string with a nil index value (index.go:88). When the index argument's reflect Kind is reflect.Invalid (untyped nil), the indexer cannot resolve an integer position, so it errors. Note: this differs from out-of-range indices, which return nil silently rather than erroring.

Solutions

  1. Default the index to a valid value: {{ index $slice ($idx | default 0) }}.
  2. Guard the index with {{ with }}: {{ with $idx }}{{ index $slice . }}{{ end }}.
  3. For string-keyed maps, prefer direct field access or ensure the key is always a string.

Example fix

// before
{{ index $slice $maybeNilIdx }}
// after
{{ with $maybeNilIdx }}{{ index $slice . }}{{ end }}
Defensive patterns

Strategy: validation

Validate before calling

{{ with $maybeNilIdx }}{{ index $slice . }}{{ end }}

Prevention

When it happens

Trigger: Calling {{ index $slice $nilVar }} where $nilVar is unset; {{ index .Params.tags .Params.missing }} where the second arg resolves to nil; multi-level indexing where one level key is nil.

Common situations: Optional front matter fields used as indices; template variables never assigned; chained index calls where an intermediate lookup returns nil and is reused as a key.

Related errors


AI-assisted analysis of gohugoio/hugo@52c9bd7908 (2026-08-09). Data as JSON: /api/errors/d617550af6c872a3. Report an issue: GitHub.

Appendix: source

Thrown at tpl/collections/index.go:88

	for _, i := range indices {
		index := reflect.ValueOf(i)
		var isNil bool
		if v, isNil = hreflect.Indirect(v); isNil {
			// See issue 10489
			// This used to be an error.
			return nil, nil
		}
		switch v.Kind() {
		case reflect.Array, reflect.Slice, reflect.String:
			var x int64
			switch index.Kind() {
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				x = index.Int()
			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
				x = int64(index.Uint())
			case reflect.Invalid:
				return nil, errors.New("cannot index slice/array with nil")
			default:
				return nil, fmt.Errorf("cannot index slice/array with type %s", index.Type())
			}
			if x < 0 || x >= int64(v.Len()) {
				// We deviate from stdlib here.  Don't return an error if the
				// index is out of range.
				return nil, nil
			}
			v = v.Index(int(x))
		case reflect.Map:
			index, err := prepareArg(index, v.Type().Key())
			if err != nil {
				return nil, err
			}

			if x := v.MapIndex(index); x.IsValid() {
				v = x
			} else {

View on GitHub (pinned to 52c9bd7908)