TheAlgorithms/Go · error

index out of range

Error message

index out of range

What it means

DynamicArray.CheckRangeFromIndex validates that an index lies within [0, Size). Put, Remove, and Get call it first and return this error instead of letting Go panic with a slice index-out-of-range at a deeper level.

Source

Thrown at structure/dynamicarray/dynamicarray.go:90

	}

	return da.ElementData[index], nil
}

// IsEmpty function is check that the array has value or not
func (da *DynamicArray) IsEmpty() bool {
	return da.Size == 0
}

// GetData function return all value of array
func (da *DynamicArray) GetData() []any {
	return da.ElementData[:da.Size]
}

// CheckRangeFromIndex function it will check the range from the index
func (da *DynamicArray) CheckRangeFromIndex(index int) error {
	if index >= da.Size || index < 0 {
		return errors.New("index out of range")
	}
	return nil
}

// NewCapacity function increase the Capacity
func (da *DynamicArray) NewCapacity() {
	if da.Capacity == 0 {
		da.Capacity = defaultCapacity
	} else {
		da.Capacity = da.Capacity << 1
	}

	newDataElement := make([]any, da.Capacity)

	copy(newDataElement, da.ElementData)

	da.ElementData = newDataElement
}

View on GitHub (pinned to 5ba447ec5f)

Solutions

  1. Validate 0 <= index < da.Size (or len(da.Slice())) before calling
  2. Fix loop bounds to i < size, not i <= size
  3. Use the array's current Size() after every mutation instead of a cached length

Example fix

// before
v, _ := arr.Get(arr.Capacity()) // index beyond size
// after
idx := arr.Capacity() - 1
if idx >= 0 && idx < arr.Size() {
    v, err := arr.Get(idx)
    if err != nil { return err }
}
Defensive patterns

Strategy: validation

Validate before calling

func inRange(da *dynamicarray.DynamicArray, i int) bool {
    return i >= 0 && i < da.Size()
}
if !inRange(arr, idx) { return ErrBadIndex }

Try / catch

if err := arr.CheckRangeFromIndex(idx); err != nil {
    return fmt.Errorf("get %d: %w", idx, err)
}
v, _ := arr.Get(idx)

Prevention

When it happens

Trigger: Calling Get(i), Put(i, v), or Remove(i) where i < 0 or i >= da.Size — e.g. indexing by the array's Capacity instead of Size, using a stale saved index after a Remove, or an off-by-one loop bound (i <= len).

Common situations: Iterating with <= instead of <; caching indexes across mutations; confusing capacity with size; porting 1-based logic into a 0-based API.

Related errors


AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02). Data as JSON: /api/errors/5df241e77e93284a. Report an issue: GitHub.