Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go: panic: runtime error: index out of range with length

The panic names the bad index and the real length. Fix loop bounds, check capacity before slicing, and keep strings and runes straight.

~5 min readGo
#go#panics#slices#runtime
Bold white headline reading OUT OF RANGE with a Go slice crate showing an amber index probe past the cyan array boundary.

Introduction & Quick Summary

A Go program crashes with a panic that names the index and the length:

code
panic: runtime error: index out of range [5] with length 3 goroutine 1 [running]: main.main() /app/main.go:9 +0x1d exit status 2

Quick answer: the loop or the index went past the end. Use range or compare against len, never cap.

go
for i := 0; i < len(items); i++ { // wrong: i <= len(items) fmt.Println(items[i]) } for _, v := range items { // usually clearer fmt.Println(v) }

The message is unusually generous: [5] with length 3 gives the exact bad index and the exact size of the thing indexed. From those two numbers the defect is usually obvious — an off-by-one loop, a slice built from a shorter source, or an index that came from a different slice. What takes longer is understanding that Go panics on index and slice bounds but never on map lookups, which is why the same code shape is safe in one place and fatal in another.

Core Mechanics, Signatures & Reproducible Setup

Valid indices for a slice or array of length n are 0 through n-1. The runtime checks every index expression — unless the compiler can prove it is safe at compile time. Reproduce both flavours:

go
package main import "fmt" func main() { s := []string{"a", "b", "c"} fmt.Println(s[3]) // panic: index out of range [3] with length 3 _ = s[:4] // panic: slice bounds out of range [:4] with capacity 3 var empty []int _ = empty[0] // panic: index out of range [0] with length 0 }

Slicing is checked against capacity, not length, for the high bound, which produces a different message:

go
s := make([]int, 2, 8) // len 2, cap 8 _ = s[1:5] // legal: 5 <= cap(s) _ = s[1:9] // panic: slice bounds out of range [:9] with capacity 8 _ = s[3:1] // panic: slice bounds out of range [3:1]
ExpressionCheckPanic text
s[i]0 <= i < len(s)index out of range [i] with length n
s[i] = vsameindex out of range [i] with length n
s[low:high]0 <= low <= high <= cap(s)slice bounds out of range [low:high]
s[low:high:max]extra high <= max <= cap(s)slice bounds out of range [::max]
str[i]byte index, i < len(str)index out of range [i] with length n
m[k]no checkreturns the zero value
arr[i] on an arraycompile-time if constantindex out of range

Key Comparison Table

Common shapes and the safe replacement for each:

Risky codePanics whenSafe form
for i := 0; i <= len(s); i++always, on the last iterationi < len(s)
s[len(s)]alwayss[len(s)-1]
s[i+1] inside a loop over slast elementif i+1 < len(s)
strings.Split(csv, ",")[2]fewer than three fieldscheck len(parts) first
resp.Items[0]empty API resultcheck len and return an error
[len(s):] on a full slicelen == cap after appendappend instead of pre-slicing

The panic text itself identifies which category you are in:

Panic textMeaningFirst thing to check
index out of range [5] with length 3index past lenloop bound
index out of range [-1]negative indexarithmetic on unsigned counters
slice bounds out of range [:4:]three-index slice too smallcap of the input
slice bounds out of range [3:2]low greater than highargument order
string index out of rangebyte offset past the endrune vs byte

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Off-by-one loops, and the version that looks right

go
// wrong in a subtle way: skips the last element instead of panicking for i := 0; i < len(s)-1; i++ { } // wrong and loud for i := 0; i <= len(s); i++ { } // right for most reads for i, v := range s { }

A loop that uses i+1 needs a bound check or a shorter range:

go
for i := 0; i < len(s)-1; i++ { if s[i] == s[i+1] { // adjacent pair } }

When len(s) is zero this loop body never runs, so the -1 is safe there; the dangerous version is for i := 0; i < len(s); i++ { _ = s[i+1] }, which panics on every non-empty input.

2. len versus cap after append

go
buf := make([]byte, 0, 4) buf = append(buf, 'a', 'b', 'c', 'd') // len 4, cap 4 buf = append(buf, 'e') // cap grows, len 5 _ = buf[:cap(buf)] // may expose uninitialised tail bytes

The classic incident is a buffer reused between requests: buf = buf[:0] resets the length, then code indexes buf[0] assuming the old data is there. Length, not capacity, is the contract. copy follows the same rule and never panics: it copies min(len(dst), len(src)) elements, so a short destination silently truncates instead of crashing — check the returned count when truncation would be a bug.

3. Slices of slices and shared backing arrays

go
a := []int{1, 2, 3, 4} b := a[1:3] // len 2, cap 3, shares memory with a b[0] = 99 // a[1] becomes 99 b = append(b, 5) // writes into a[3]

A slice carries a pointer, a length and a capacity. a[1:3] keeps the capacity of the tail, so an append can silently overwrite the parent. slices.Clone or append([]int(nil), b...) breaks the link. This also explains panics that appear only under load: a slice shared across goroutines is mutated while another reads it, so a length check passes and the subsequent index still panics.

4. Strings are bytes, not characters

go
name := "한글" fmt.Println(len(name)) // 6 fmt.Println(name[0]) // 0xED, the first byte of the first rune fmt.Println(name[2:]) // may split a UTF-8 sequence runes := []rune(name) fmt.Println(string(runes[0])) // 한

len(s) on a string is a byte count, so s[len(s)-1] is the last byte, not the last character, and s[0:1] can produce invalid UTF-8. Convert to []rune when you need characters, and use utf8.RuneCountInString when you need a count. Range over a string yields byte offsets and runes, which is why for i, r := range s behaves differently from for i := 0; i < len(s); i++.

5. Data from outside: JSON, CSV, split results

go
type Response struct { Items []struct{ ID int } `json:"items"` } func firstID(body []byte) (int, error) { var r Response if err := json.Unmarshal(body, &r); err != nil { return 0, fmt.Errorf("decode: %w", err) } if len(r.Items) == 0 { return 0, errors.New("no items in response") } return r.Items[0].ID, nil }

strings.Split("", ",") returns one empty string, not zero strings, so parts[1] panics on empty input — a favourite of CSV and header parsers. Validate the field count before indexing, and return an error rather than letting the process die. The JSON formatter shows whether items is an array or null, and the CSV to JSON converter reproduces a short row locally before it reaches production.

6. Recovering, and when not to

A panic in a goroutine cannot be recovered by an outer recover; each goroutine needs its own. For a server, per-request recovery is a reasonable safety net:

go
func safe(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if v := recover(); v != nil { slog.Error("panic", "value", v, "path", r.URL.Path) http.Error(w, "internal error", http.StatusInternalServerError) } }() handler.ServeHTTP(w, r) }) }

That keeps the process alive but hides the bug from tests. Fix the index inside the handler; keep recover at the boundary. Bounds checks cost a predictable branch and are the first thing a microbenchmark will show as removable with -gcflags=-B — doing so trades a crash for silent memory corruption and is never worth it in application code.

Common Compilation/Runtime Mistakes & Version Gotchas

Indexing nil slices. var s []int; s[0] panics with length 0. len(s) on a nil slice is 0, so the length check is the guard.

Assuming a map lookup panics. It does not; it returns the zero value and ok == false. Code that guards map reads like slice reads usually hides a real bug behind a zero value.

Ignoring the second return of a type assertion. v := i.(T) panics; v, ok := i.(T) does not.

Using cap as a length. Only slicing reads capacity; indexing and len do not.

Version notes. Go 1.21 changed loop variable semantics: before 1.21 the loop variable was shared across iterations, so closures captured the last value, and code that stored &s[i] or used goroutines closed over i produced both wrong results and occasional out-of-range panics. Go 1.22 made each iteration's variable distinct. slices and maps in the standard library (1.21) replace most hand-written boundary code — slices.Index returns -1 instead of panicking, which is worth preferring.

Reference material: The Go Programming Language Specification and Slices: usage and internals.

Official references

primary documentation

The Go documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.