krahets/hello-algo · error

索引越界

Error message

索引越界

What it means

A Go panic triggered by the get() method of a custom dynamic-array list when index falls outside [0, arrSize). Go has no exceptions, so the library uses panic() to signal an unrecoverable bounds violation. The panic must be caught with a deferred recover() or — preferably — prevented by bounds-checking before the call. The check uses arrSize (logical length), not arrCapacity (allocated length), so accessing any slot between arrSize and arrCapacity-1 also panics.

Source

Thrown at 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

  1. Validate index >= 0 && index < l.size() before calling get()
  2. Use l.size() as the loop upper bound, not capacity()
  3. If panic recovery is needed, wrap the call in a deferred recover() goroutine-local handler

Example fix

// before
val := l.get(i)

// after
if i >= 0 && i < l.size() {
    val := l.get(i)
} else {
    val = -1
}
Defensive patterns

Strategy: validation

Validate before calling

if index >= 0 && index < l.size() {
    val := l.get(index)
} else {
    val = -1
}

Try / catch

func safeGet(l *myList, index int) (val int, err error) {
    defer func() {
        if r := recover(); r != nil {
            val = -1
            err = fmt.Errorf("index %d out of bounds", index)
        }
    }()
    return l.get(index), nil
}

Prevention

When it happens

Trigger: Calling get(i) with i >= l.size(); passing a negative index (common in ports from Python); using a loop variable that exceeds arrSize after elements were removed.

Common situations: Looping to capacity() instead of size(); reusing a stale index after remove(); porting Python code that relies on negative indexing which Go does not support.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/9a4b272e73c61668. Report an issue: GitHub.