Ad Space — Top Banner

slice bounds out of range

Go Programming Language

Severity: Critical

What Does This Error Mean?

Go panics when you try to access a slice index that doesn't exist. Your index is either negative or larger than the slice length. This is a runtime error — it crashes your program immediately.

Affected Models

  • Go 1.21
  • Go 1.22
  • Go 1.23
  • Go 1.24

Common Causes

  • Accessing s[n] when n is greater than or equal to len(s)
  • Using a slice expression like s[a:b] where b is greater than len(s)
  • Off-by-one error — forgetting that slices are zero-indexed
  • Slicing a nil or empty slice without checking its length first
  • Passing an index from external input without validating its range

How to Fix It

  1. Read the full panic message — it tells you exactly which index was out of range.

    Example: 'runtime error: index out of range [5] with length 3' means you tried index 5 on a 3-element slice.

  2. Add a bounds check before accessing the index: if i < len(s) { ... }

    This is the most common fix. Never assume a slice has the length you expect.

  3. For slice expressions s[a:b], ensure b is less than or equal to len(s).

    Use s[a:] to slice to the end safely, or cap b with min(b, len(s)).

  4. Check for nil or empty slices before indexing: if len(s) == 0 { return }

    A nil slice has length 0. Treat nil and empty slices the same way.

  5. Use a loop with range instead of manual indexing when iterating.

    for i, v := range s {} is always safe — Go controls the index for you.

When to Call a Professional

If this panic appears in production code handling critical data, have a senior developer audit the affected function. Unchecked index access can be a security risk if inputs come from users.

Frequently Asked Questions

What does 'slice bounds out of range [:5] with length 3' mean?

You tried to slice up to index 5, but the slice only has 3 elements. The upper bound of a slice expression cannot exceed the slice's length. Fix: check len(s) before slicing.

Can slice bounds panics be recovered with recover()?

Yes — you can catch this panic using defer and recover(). But that is a band-aid, not a fix. The real fix is adding proper bounds checks before the access.

How do I safely get the last element of a slice?

Use s[len(s)-1], but always check len(s) > 0 first. If the slice is empty, this will panic. A safe helper: if len(s) > 0 { last := s[len(s)-1] }