Fixing 'panic: runtime error: slice bounds out of range' in Go

beginner🔷 Go2026-06-14| Go (Golang) Runtime, all Operating Systems

Error Message

panic: runtime error: slice bounds out of range [:5] with length 3
#golang#slice#panic#debugging#runtime

The Problem: Sliding Past the EdgeGo slices are powerful, but they have one non-negotiable rule. You cannot access or slice beyond their actual length. If you try to grab a sub-slice larger than the original, the Go runtime pulls the emergency brake. It triggers a panic to prevent memory corruption. Think of it as a safety rail that keeps your program from reading garbage data.

Usually, this happens because of a bad assumption. You might expect an API to return 100 log entries, but it only returns 3. If your code immediately tries to process the first 10 items, it hits a wall.

The Exact Error Message```

panic: runtime error: slice bounds out of range [:5] with length 3


In this scenario, the program tried to slice from the start up to index 5 (`[:5]`). However, the slice only had 3 elements. Since indices 3, 4, and 5 don't exist, the program crashed instantly.
## Reproducing the CrashHere is a snippet that recreates the failure. This pattern is common when developers try to 'preview' data without checking the source size first.

package main

import "fmt"

func main() { // Simulation: Data fetched from a database or API userIDs := []string{"user_1", "user_2", "user_3"}

// Goal: Display the top 5 users
// This line will cause a panic
topFive := userIDs[:5]

fmt.Println(topFive)

}


Running `go run main.go` triggers the `slice bounds out of range` panic. The program dies because `len(userIDs)` is only 3, making index 5 an impossible target.
## How to Fix It### 1. The Classic Length CheckThe most reliable fix is to verify the slice length before you touch it. It’s simple, defensive, and works in every Go version. Always calculate your 'end' index based on what is actually available.

limit := 5 if len(userIDs) < limit { limit = len(userIDs) }

topFive := userIDs[:limit] fmt.Println(topFive)


### 2. The Modern Approach (Go 1.21+)If you are using Go 1.21 or newer, the built-in `min` function makes this much cleaner. It handles the comparison logic in a single, readable line.

// No imports needed for min limit := min(5, len(userIDs)) topFive := userIDs[:limit]


### 3. Build a Safe Slice UtilityFor projects that handle heavy data processing, a helper function prevents code duplication and keeps your business logic tidy.

func safeSlice(s []string, start, end int) []string { if start > len(s) { return nil } if end > len(s) { end = len(s) } return s[start:end] }

// Usage: topFive := safeSlice(userIDs, 0, 5)


## Slicing vs. Direct AccessYou might also encounter `index out of range [5] with length 3`. While it looks similar, this happens during direct access (e.g., `id := userIDs[5]`) rather than slicing. The fix remains the same: always check `len(slice)` before accessing a specific index. Never assume an index exists just because the code worked during a single test run.
## Validation StrategyBefore deploying your fix, test these three specific scenarios to ensure your logic is bulletproof:
- **Large Input:** If the slice has 50 items, `[:5]` should return exactly 5.- **Small Input:** If the slice has 2 items, `[:5]` should return 2 items, not 5.- **Empty Input:** If the slice is `nil` or length 0, your code should return an empty slice rather than crashing.Integrate these checks into your `go test` suites to prevent regressions during future refactors.
## Lessons for Production- **Treat Inputs as Hostile:** Never trust the length of data coming from an external API or database.- **Let Range Do the Work:** Use `for i, val := range slice` whenever possible. It handles bounds safety automatically.- **Fail Fast:** If a slice is empty and your function can't proceed, return an error immediately. Don't let the nil or empty slice drift deeper into your logic.- **Automate Checks:** Use `golangci-lint` in your CI/CD pipeline to flag potential out-of-bounds errors before they reach production.

Related Error Notes