Go

Fix Go "panic: runtime error: index out of range" — Slice, Array, String, and Slice-Bounds Panics

This panic is the runtime catching an index the compiler could not rule out: the index was in range for the values the program was tested with and out of range for the value it actually received, or a length changed and the code that walks it did not change with it. Each section below takes one shape — an index too large, a negative index, an index equal to the length, a string index, a slice bound, an off-by-one loop — shows the exact output it prints, and gives the check or the loop form that keeps the index inside the value it indexes.

Written November 20, 2026 · Tested with Go 1.26.4 · 3 min read

By the end of this guide
  • The first failure: an index past the end of a slice
  • Reading the message: the index, the length, and the line
  • A negative index: below the range is out of range
  • An index equal to the length: the off-by-one boundary

What this guide is

panic: runtime error: index out of range [5] with length 3 is a run-time panic: the program built, started, and then evaluated an index expression whose index was outside the value it indexed. The specification gives the rule in one line: the index x is in range if 0 <= x < len(a), otherwise it is out of range — and for an array, a slice, or a string, an index that is out of range at run time causes a run-time panic. Every shape in this guide is that one rule met from a different direction: an index past the end, an index below zero, an index that equals the length and is therefore already past the last element, an index into a string counted in bytes, and the neighboring family — slice expressions, whose bounds are judged against capacity as well as length and whose panic reads slice bounds out of range instead.

One member of the family is not a panic at all. When the index is a constant indexing an array or a constant string and it is out of range, the program never builds: the same defect arrives as a compile error, earlier and cheaper. The difference between the compile error and the panic is not the size of the mistake — it is whether the index's value was known at compile time. A variable index, an index read from input, an index computed from a length that changed at run time: those reach the runtime check, and the panic is that check firing.

The examples here use Go 1.26.4. Every example lives in a single file named main.go inside one module, created once from an empty directory:

Terminal
$ mkdir indexrange
$ cd indexrange
$ go mod init example.com/indexrange
go: creating new go.mod: module example.com/indexrange

Each program that follows replaces the contents of that main.go. The panic transcripts are shown as printed by go run -trimpath main.go: the -trimpath flag only changes how file positions print in the trace — ./main.go:8 here, where a plain run prints the same line number behind the full directory path on your machine. Tested with Go 1.26.4.

The first failure: an index past the end of a slice

The smallest program that earns the panic indexes a three-element slice at position 5, with the index held in a variable so the compiler cannot settle it:

Go
// main.go
package main

import "fmt"

func main() {
    a := []int{10, 20, 30}
    i := 5
    fmt.Println(a[i])
}
Terminal
$ go run -trimpath main.go
panic: runtime error: index out of range [5] with length 3

goroutine 1 [running]:
main.main()
    ./main.go:8 +0x9
exit status 2

The message carries both numbers that matter: the index that was asked for, [5], and the length it was asked against, with length 3. A slice of length 3 has exactly three valid indices — 0, 1, and 2 — because the rule is 0 <= x < len(a), strict on the right. Index 5 is not a near miss; there is no element at 3 or 4 either. The runtime checks the index before the access, finds it out of range, and panics rather than reading whatever memory sits past the slice's elements.

In a real program the variable index is the shape to expect: a position parsed from input, an ID used as an index, a count kept in a second variable that no longer matches the slice. The fix is a bounds check at the point where the index arrives from somewhere the compiler cannot follow — if i >= 0 && i < len(a) before the access, with the out-of-range case handled as the bad input it is — or a restructure so the index is produced by ranging over the slice itself, which cannot produce an out-of-range index. The fixed program at the end of this guide shows both.

Reading the message: the index, the length, and the line

Three things in the output are worth reading closely.

First, the bracketed number is the index value at run time, not a position in the source. [5] is what i held when the expression ran. When the number surprises you — larger than any length in the program, or negative — the defect is upstream, where that value was computed or read, and the trace line is only where it was used.

Second, with length 3 is the length of the specific value indexed, at that moment. Slices change length as a program runs: an append that did not happen on an error path, a filter that removed elements, a sub-slice taken earlier. The length in the message is the length then, so compare it against the length the code at that line assumed, not against the length the slice had when it was created.

Third, this failure is a panic, which places it inside the panic mechanism — unlike a fatal error, it unwinds the stack, runs deferred calls, and can be caught by recover. The contrast section below shows exactly that. Catching it is a diagnostic tool and a last-resort guard at a program boundary; it is not the fix for an index the program itself computed, because the check that would prevent it is one comparison at the access.

A negative index: below the range is out of range

The rule's left half, 0 <= x, fails the same way:

Go
// main.go
package main

import "fmt"

func main() {
    a := []int{10, 20, 30}
    i := -1
    fmt.Println(a[i])
}
Terminal
$ go run -trimpath main.go
panic: runtime error: index out of range [-1]

goroutine 1 [running]:
main.main()
    ./main.go:8 +0x10
exit status 2

Note what the message omits: for a negative index there is no with length clause, because the length is not what the index failed against — no length makes -1 valid. Go has no from-the-end indexing: the last element is a[len(a)-1], written out, not a[-1]. Negative indices reach real code as arithmetic: a predecessor computed as i - 1 on the first iteration, a difference of two positions, an offset applied before the element it offsets from is known to exist. The guard is the same bounds check, and the left half of it — i >= 0 — is the half that matters here; a check written as only i < len(a) passes -1 straight through to this panic.

An index equal to the length: the off-by-one boundary

The most common member of the family is the index that equals the length:

Go
// main.go
package main

import "fmt"

func main() {
    a := []int{10, 20, 30}
    fmt.Println(a[len(a)])
}
Terminal
$ go run -trimpath main.go
panic: runtime error: index out of range [3] with length 3

goroutine 1 [running]:
main.main()
    ./main.go:7 +0x9
exit status 2

[3] with length 3 looks like it should fit, and the strict inequality is why it does not: indices run from 0 to len(a) - 1, so the length itself is the first invalid index, not the last valid one. This shape is the boundary form of the off-by-one error — a hand-off where one side counts elements (there are 3) and the other side indexes them (the last is at 2), a page number or a rank used directly as an index, a len result passed where a last-index was wanted. Where the last element is the intent, write a[len(a)-1] — and guard the empty case, because at length 0 that expression is the negative-index panic above. Where a count is the intent, the count is not an index at all, and keeping the two in differently named variables is the repair that survives the next edit.

A constant index: the same defect as a compile error

Replace the slice with an array and the variable index with a constant and the failure moves from run time to compile time:

Go
// main.go
package main

import "fmt"

func main() {
    a := [3]int{10, 20, 30}
    fmt.Println(a[5])
}
Terminal
$ go run -trimpath main.go
# command-line-arguments
./main.go:7:16: invalid argument: index 5 out of bounds [0:3]

There is no panic and no run: the program does not build. The specification's index rules require a constant index to be in range for arrays and for constant strings, so the compiler rejects a[5] against a [3]int outright, and the message gives the valid interval, [0:3]. This is the same out-of-range defect as the first section's, caught at the earliest possible moment because every value involved was known at compile time.

The practical consequence cuts the other way as well: the shapes that panic are precisely the ones where some value was not constant — the index, or the length. A slice's length is a run-time fact even when its literal looks fixed, because slices are resized, filtered, and passed between functions; that is why the first program in this guide, whose slice is written out in full on the line above the index, still panics instead of failing to compile — its index was a variable. When a test or a review asks why the compiler did not catch an out-of-range access, the answer is in which of the two values it could not know.

Indexing a string: bytes, and the same length rule

A string indexes by byte, and its indices obey the same rule:

Go
// main.go
package main

import "fmt"

func main() {
    s := "hello"
    i := 10
    fmt.Println(s[i])
}
Terminal
$ go run -trimpath main.go
panic: runtime error: index out of range [10] with length 5

goroutine 1 [running]:
main.main()
    ./main.go:8 +0x9
exit status 2

The specification states the string case directly: if the index is out of range at run time, a run-time panic occurs, and a[x] is the byte value at index x, of type byte. Two consequences follow. The length in the message is the length in bytes — "hello" has length 5, and index 10 fails against it exactly as the slice index did. And a string index that is in range still yields a byte, not a character: for text where a character can occupy more than one byte, an in-range byte index can land inside a character, which is a wrong-answer bug rather than a panic. Code that walks text character by character belongs in a for–range loop over the string, which yields each character's byte position and the character itself, and cannot produce an out-of-range index. Code that works in bytes — protocols, hashes, fixed formats — indexes strings the way it indexes slices, with the same bounds check.

Slice bounds: the high bound is judged against capacity

Slicing is the neighboring operation with its own panic wording. A simple slice expression a[low:high] on a slice fails like this:

Go
// main.go
package main

import "fmt"

func main() {
    a := []int{10, 20, 30}
    fmt.Println(a[0:5])
}
Terminal
$ go run -trimpath main.go
panic: runtime error: slice bounds out of range [:5] with capacity 3

goroutine 1 [running]:
main.main()
    ./main.go:7 +0x36
exit status 2

The message says with capacity 3, not with length 3, and that word is the rule: for slices, the specification sets the upper index bound of a slice expression at the slice's capacity, cap(a), rather than its length. The indices are in range if 0 <= low <= high <= cap(a) for a slice operand. Here capacity and length are both 3, so 5 fails against either — but they are not always equal, and the fixed program at the end of this guide slices a length-3, capacity-5 slice out to its capacity and succeeds, producing a length-5 result whose last two elements are the zero values sitting in the allocated space beyond the original length. That is legal, and it is also a decision to make on purpose: extending a slice into its capacity exposes elements the length said were not there yet.

The same wording difference is the diagnostic: an index out of range message names an indexing failure judged against a length; a slice bounds out of range message names a slicing failure judged, for slices, against a capacity. When the capacity in the message is larger than the length you expected, the slice you are holding is a sub-slice or a make result whose capacity was set somewhere else — and len and cap are different facts about it from then on.

Slice bounds: a low bound past the high bound

The bounds must also be in order. With both bounds held in variables, a low bound above the high bound reaches the runtime check:

Go
// main.go
package main

import "fmt"

func main() {
    a := []int{10, 20, 30}
    lo := 2
    hi := 1
    fmt.Println(a[lo:hi])
}
Terminal
$ go run -trimpath main.go
panic: runtime error: slice bounds out of range [2:1]

goroutine 1 [running]:
main.main()
    ./main.go:9 +0x36
exit status 2

The message shows the pair as written, [2:1], with no capacity clause: the failure is the ordering, low <= high, which the in-range condition requires before either bound is compared against the capacity. Written with constants, a[2:1] does not get this far — constant slice indices must be in range relative to each other, so that form is a compile error, and only the variable form panics. In real code the pair arrives as a window: a start and an end computed from different facts — a match position and a limit, a page start and a total — where the empty or reversed case was never separated out. An empty window is a[2:2], which is legal and yields an empty slice; a reversed window is this panic. The guard is to establish lo <= hi — clamping or branching on the empty case — before the slice expression, at the point where the two values first meet.

Three-index slices: the max bound sets the capacity

The full slice expression a[low:high:max] adds a third bound that controls the result's capacity:

Go
// main.go
package main

import "fmt"

func main() {
    a := []int{10, 20, 30, 40, 50}
    fmt.Println(a[0:2:10])
}
Terminal
$ go run -trimpath main.go
panic: runtime error: slice bounds out of range [::10] with capacity 5

goroutine 1 [running]:
main.main()
    ./main.go:7 +0x46
exit status 2

The specification's rule for the full form is that the indices are in range if 0 <= low <= high <= max <= cap(a), and the resulting slice has length high - low and capacity max - low. Here max is 10 against a capacity of 5, so the expression panics, and the message isolates the offending bound as [::10] — the two empty slots are the low and high bounds, which were in range. The third index exists to cap how far the result can be extended by append: a sub-slice taken as a[0:2:2] cannot append into the parent slice's remaining elements, because its capacity ends where its length does. A max computed from a length or a count rather than from cap(a) is the usual source of this shape — the bound must be stated in the operand's capacity terms, and a[low:high:cap(a)] is the largest legal form.

The off-by-one loop: <= against a length

The loop form of the equal-to-length shape, and the version most often met in the wild:

Go
// main.go
package main

import "fmt"

func main() {
    a := []int{10, 20, 30}
    for i := 0; i <= len(a); i++ {
        fmt.Println(a[i])
    }
}
Terminal
$ go run -trimpath main.go
10
20
30
panic: runtime error: index out of range [3] with length 3

goroutine 1 [running]:
main.main()
    ./main.go:8 +0x9b
exit status 2

The output shows the shape's signature: the program works, visibly, before it fails. It prints all three elements correctly — 10, 20, 30 — and then runs one iteration too many, at i equal to 3, because the condition i <= len(a) admits the length itself as an index. The condition for an index loop is i < len(a): the strict form, matching the strict inequality in the index rule. One character is the whole defect, which is why this shape survives review — the loop reads as "go up to the length", and going up to the length is exactly the error.

The stronger repair is to not hold the index at all. for _, v := range a yields each element in order and has no condition to write wrong; for i, v := range a yields the index alongside the value when the position itself is needed, and every index it yields is in range by construction. An explicit index loop earns its place when the traversal is not a plain front-to-back walk — stepping by more than one, walking backwards, moving two indices toward each other — and those loops are the ones whose conditions and update steps deserve the careful read this shape teaches.

The contrast: a panic can be recovered

Unlike the fatal errors the runtime reports for states no goroutine can leave, an index panic is an ordinary panic, and a deferred recover catches it:

Go
// main.go
package main

import "fmt"

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("recovered:", r)
        }
    }()
    a := []int{10, 20, 30}
    i := 5
    fmt.Println(a[i])
    fmt.Println("after")
}
Terminal
$ go run -trimpath main.go
recovered: runtime error: index out of range [5] with length 3

The deferred function prints the recovered value — the panic's message, verbatim — and the program exits cleanly; after does not print, because the panic still unwound the function that raised it, and execution resumes after the function returns, not at the line that panicked. This has two legitimate uses: as a probe, confirming which access in a suspect path panics and with what index, and as a boundary guard, where a program isolates work it does not control and converts a panic into an error at that boundary. Inside ordinary code that computed the index itself, a recover around the access is strictly worse than the bounds check it replaces: the check states the condition, handles the case where it stands, and costs one comparison — while the recovered version discovers the same fact by unwinding, and says nothing about what the program should do with the element it failed to reach.

The fixed program

One program that applies each fix at once — a bounds check where an outside index arrives, a range loop for the plain walk, and a deliberate extension into capacity with its len and cap printed so the decision is visible:

Go
// main.go
package main

import "fmt"

func main() {
    a := make([]int, 3, 5)
    a[0] = 10
    a[1] = 20
    a[2] = 30

    i := 5
    if i >= 0 && i < len(a) {
        fmt.Println(a[i])
    } else {
        fmt.Println("index", i, "out of range for length", len(a))
    }

    for _, v := range a {
        fmt.Println(v)
    }

    b := a[:5]
    fmt.Println(b)
    fmt.Println(len(b), cap(b))
}
Terminal
$ go run main.go
index 5 out of range for length 3
10
20
30
[10 20 30 0 0]
5 5

The bounds check takes the branch the panic would have replaced, and prints why: index 5 against length 3, handled as a fact about the input rather than an end to the program. The range loop prints the three elements with no index variable in the code at all. The extension a[:5] succeeds because 5 is within the slice's capacity — the result has length 5 and capacity 5, and its last two elements are the zero values that were allocated but never assigned — which is the capacity rule from the slicing sections used deliberately, with the printed len and cap stating what was done.

The fixes, ranked

Range where the walk is a walk. for _, v := range a, or for i, v := range a when the position is needed. This removes the index as a thing the code can get wrong, rather than checking it, and it is the fix for the off-by-one loop and for most hand-written counting loops over a slice, an array, or a string. It is ranked first because a construction that cannot produce the defect outranks a check that catches it.

Check the bounds where an index arrives from outside the walk. if i >= 0 && i < len(a) at the access, both halves present — the left half is the negative-index fix, the right half is the too-large and equal-to-length fix. This fits indices parsed from input, positions stored and retrieved, and arithmetic results like i - 1 and start + offset, where no loop structure produced the value. Handle the failing branch as the bad input or exhausted case it is; a check that falls through to the access anyway is this guide's panic with extra steps.

Keep counts and indices in different variables, named for what they are. A length, a count, a rank, and a page number are not indices, and the equal-to-length shape is what happens when one is used as another. Where a last element is wanted, a[len(a)-1] with an empty check; where a position in a list presented to a reader is wanted, convert at the presentation line — i + 1 for display, stored data stays zero-based — and never store the display form.

State slice bounds in the operand's terms, and establish their order first. Before a[low:high], the facts to have are 0 <= low, low <= high, and — for a slice operand — high <= cap(a); for the three-index form, max <= cap(a) as well. Clamp or branch where the bounds are computed, not at the slice expression. Remember which bound the operation uses: indexing judges against len, slicing a slice judges its high bound against cap, and confusing the two is how a length-correct program still panics on a slice expression.

Do not answer the panic with recover in code that computed the index. The recovered program above is a probe and a boundary pattern. Around your own indexing, recover converts a one-line check into an unwinding, discards the position the program was in, and leaves the next caller to rediscover the same fact. Fix the condition; reserve recover for boundaries around work whose panics you cannot prevent by construction.

Which fix for which cause

What the message and code show Cause Fix
index out of range [5] with length 3, index in a variable An index past the end, from input or arithmetic Bounds check both halves, or range instead
index out of range [-1], no length clause A negative index, usually i - 1 or a difference The i >= 0 half of the check; guard the first-element case
index out of range [3] with length 3 A count or length used as an index len(a) - 1 for the last element; keep counts out of index variables
Compile error index 5 out of bounds [0:3] A constant index the compiler can judge Fix the constant or the size; the program never ran
index out of range [10] with length 5 on a string A byte index past the end of a string Bounds check for byte work; range the string for character work
slice bounds out of range [:5] with capacity 3 A high bound past the operand's capacity State the bound against cap(a); extend capacity deliberately or not at all
slice bounds out of range [2:1] A low bound above the high bound Establish low <= high; branch the empty case before slicing
slice bounds out of range [::10] with capacity 5 A three-index max past the operand's capacity Set max from cap(a); the largest legal form is a[low:high:cap(a)]
Correct output, then [3] with length 3 at the loop line i <= len(a) in an index loop i < len(a), or range the slice

Checklist

  • Read both numbers in the message before touching code: the bracketed index is the value that ran, and with length is the length of the value it ran against, at that moment.
  • Find where the index was produced, not only where it was used: input, arithmetic, a stored position, and a count reused as an index are the four sources, and the trace names none of them.
  • Check any hand-written bounds test for both halves: i < len(a) alone admits every negative index, and i >= 0 alone admits every large one.
  • Audit index loops for <= against a length, and for conditions written against a length captured before the slice was resized.
  • For every slice expression, name the operand's len and cap separately, and state which one the bound must satisfy — then check the bounds are in order before either is compared.
  • Where a three-index slice appears, read the max as a capacity claim about the operand, and confirm it was derived from cap(a) and not from a length or a count.

Sources

  • The Go Programming Language Specification — for index expressions (the index is in range if 0 <= x < len(a), otherwise it is out of range; a constant index must be in range for arrays and constant strings; an out-of-range index at run time causes a run-time panic for arrays, slices, and strings; a string index yields the byte at that index), for slice expressions (simple form: for slices the upper bound is the capacity cap(a) and the indices are in range if 0 <= low <= high <= cap(a); full three-index form: the indices are in range if 0 <= low <= high <= max <= cap(a) and the result has capacity max - low; constant indices must be in range relative to each other), and for length and capacity (len and cap return a result of type int; the capacity of a slice is the number of elements for which there is space allocated in the underlying array, and 0 <= len(s) <= cap(s) always holds).

Keep Exploring