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.

Introduction & Quick Summary
A Go program crashes with a panic that names the index and the length:
panic: runtime error: index out of range [5] with length 3
goroutine 1 [running]:
main.main()
/app/main.go:9 +0x1d
exit status 2Quick answer: the loop or the index went past the end. Use range or compare against len, never cap.
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:
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:
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]| Expression | Check | Panic text |
|---|---|---|
s[i] | 0 <= i < len(s) | index out of range [i] with length n |
s[i] = v | same | index 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 check | returns the zero value |
arr[i] on an array | compile-time if constant | index out of range |
Key Comparison Table
Common shapes and the safe replacement for each:
| Risky code | Panics when | Safe form |
|---|---|---|
for i := 0; i <= len(s); i++ | always, on the last iteration | i < len(s) |
s[len(s)] | always | s[len(s)-1] |
s[i+1] inside a loop over s | last element | if i+1 < len(s) |
strings.Split(csv, ",")[2] | fewer than three fields | check len(parts) first |
resp.Items[0] | empty API result | check len and return an error |
[len(s):] on a full slice | len == cap after append | append instead of pre-slicing |
The panic text itself identifies which category you are in:
| Panic text | Meaning | First thing to check |
|---|---|---|
index out of range [5] with length 3 | index past len | loop bound |
index out of range [-1] | negative index | arithmetic on unsigned counters |
slice bounds out of range [:4:] | three-index slice too small | cap of the input |
slice bounds out of range [3:2] | low greater than high | argument order |
string index out of range | byte offset past the end | rune vs byte |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Off-by-one loops, and the version that looks right
// 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:
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
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 bytesThe 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
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
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
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:
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 documentationThe Go documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo: x509 certificate signed by unknown authority
Go cannot build a chain to a trusted root: no CA bundle in the image, a private CA, or a missing intermediate. Install roots or set RootCAs.
Go: fatal error: concurrent map writes in goroutines
The runtime catches two writes to one map and stops the process. Guard access with a mutex, use sync.Map for caches, or give one owner.
Go: import cycle not allowed
Go forbids cycles in the package import graph. Break them by extracting shared types, declaring interfaces where consumed, or inverting init registration.
Go: http: superfluous response.WriteHeader call
net/http logs this when a handler writes the status twice. It almost always marks a later status write that was silently ignored, or no return.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.