krahets/hello-algo · error
索引越界
Error message
索引越界
What it means
Panic thrown by get(index) on the educational myList (Traditional Chinese build) when the requested index is outside [0, arrSize-1]. Reading past the live element count would touch uninitialized/stale slots, so the method enforces the bounds up front and aborts with '索引越界' (index out of bounds). get() is read-only so it cannot shrink the list, but it still requires a currently-valid index.
Source
Thrown at zh-hant/codes/go/chapter_array_and_linkedlist/my_list.go:39
extendRatio: 2, // 每次串列擴容的倍數
}
}
/* 獲取串列長度(當前元素數量) */
func (l *myList) size() int {
return l.arrSize
}
/* 獲取串列容量 */
func (l *myList) capacity() int {
return l.arrCapacity
}
/* 訪問元素 */
func (l *myList) get(index int) int {
// 索引如果越界,則丟擲異常,下同
if index < 0 || index >= l.arrSize {
panic("索引越界")
}
return l.arr[index]
}
/* 更新元素 */
func (l *myList) set(num, index int) {
if index < 0 || index >= l.arrSize {
panic("索引越界")
}
l.arr[index] = num
}
/* 在尾部新增元素 */
func (l *myList) add(num int) {
// 元素數量超出容量時,觸發擴容機制
if l.arrSize == l.arrCapacity {
l.extendCapacity()
}View on GitHub (pinned to 69932aed18)
Solutions
- Confirm 0 <= index < l.size() before calling get().
- Prefer toArray() and slice access when you need bulk reads with safe bounds.
- Recompute size() immediately before indexing if the list may have changed.
- Clamp or reject external indices at the input boundary.
Example fix
// before: panics when index >= size
v := l.get(idx)
// after
if idx >= 0 && idx < l.size() {
v := l.get(idx)
} Defensive patterns
Strategy: validation
Validate before calling
func canGetAt(l *myList, index int) bool {
return index >= 0 && index < l.size()
}
if canGetAt(l, idx) {
v = l.get(idx)
} Try / catch
defer func() {
if r := recover(); r != nil {
// index out of range on get
}
}()
v = l.get(idx) Prevention
- Always bounds-check before get(); prefer toArray() + slice for bulk reads.
- Re-read size() before indexing if the list may have shrunk.
- Clamp untrusted indices at the input boundary.
When it happens
Trigger: Calling get() on an empty list; passing an index >= size after elements were removed; using a cached size that predates a shrink; off-by-one in an inclusive upper loop bound.
Common situations: Peeking the last element with get(size()-1) after a concurrent/logical removal made size() smaller; deserializing an index from untrusted input without clamping; iterating with `i <= size()` instead of `i < size()`.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/a251f0199bcaf8a4.
Report an issue: GitHub.