krahets/hello-algo · error
Index out of bounds
Error message
Index out of bounds
What it means
`get(index)` in the English `myList` panics with "Index out of bounds" when the requested position is outside `[0, arrSize-1]`. It is the read-side analogue of the bounds check on a real dynamic array. A bad index aborts the goroutine via `panic`.
Source
Thrown at en/codes/go/chapter_array_and_linkedlist/my_list.go:39
extendRatio: 2, // Multiple by which the list capacity is extended each time
}
}
/* Get list length (current number of elements) */
func (l *myList) size() int {
return l.arrSize
}
/* Get list capacity */
func (l *myList) capacity() int {
return l.arrCapacity
}
/* Update element */
func (l *myList) get(index int) int {
// If the index is out of bounds, throw an exception, as below
if index < 0 || index >= l.arrSize {
panic("Index out of bounds")
}
return l.arr[index]
}
/* Add elements at the end */
func (l *myList) set(num, index int) {
if index < 0 || index >= l.arrSize {
panic("Index out of bounds")
}
l.arr[index] = num
}
/* Direct traversal of list elements */
func (l *myList) add(num int) {
// When the number of elements exceeds capacity, trigger the extension mechanism
if l.arrSize == l.arrCapacity {
l.extendCapacity()
}View on GitHub (pinned to 69932aed18)
Solutions
- Gate every read with `0 <= index < l.size()`.
- Loop with `i < l.size()`, never `i <= l.size()`.
- Use `size()`, not `capacity()`, for valid-index math.
- Recover at API boundaries that accept caller-supplied indices.
Example fix
// before
v := l.get(i) // panics "Index out of bounds"
// after
if i >= 0 && i < l.size() {
v = l.get(i)
} Defensive patterns
Strategy: validation
Validate before calling
if i < 0 || i >= l.size() {
return 0, errors.New("index out of bounds")
}
return l.get(i), nil Type guard
func (l *myList) validIndex(i int) bool {
return i >= 0 && i < l.arrSize
} Try / catch
defer func() {
if r := recover(); r != nil {
// return a zero value / error instead of crashing on a bad read
}
}()
v = l.get(i) Prevention
- Use size() (not capacity()) for all valid-index math.
- Loop with `i < l.size()`, never `<=`.
- Recompute indices after any mutating operation.
When it happens
Trigger: Reading with `index < 0` or `index >= arrSize`; reading from an empty list; using the backing capacity rather than the logical size.
Common situations: Off-by-one loop bounds, confusing `capacity()` with `size()`, or a stale index held across an `add`/`insert`/`remove` that changed the size.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/79c1bcb67d7f3c69.
Report an issue: GitHub.