Negative Slice Index

runtime error: index out of range [-1]

Quick Answer

Go does not support negative indexing like Python. Use len(s)-1 to access the last element.

Why This Happens

Unlike Python, Go does not interpret negative indices as counting from the end of the slice. A negative index is always out of bounds and causes a runtime panic. Use len(s)-1 to get the last element.

The Problem

func main() {
    s := []int{1, 2, 3}
    fmt.Println(s[-1]) // runtime error: index out of range
}

The Fix

func main() {
    s := []int{1, 2, 3}
    fmt.Println(s[len(s)-1]) // prints 3
}

Step-by-Step Fix

  1. 1

    Identify the negative index

    Find the line using a negative index to access a slice or array.

  2. 2

    Replace with len-based access

    Use len(s)-1 for the last element, len(s)-2 for the second to last, and so on.

  3. 3

    Add bounds checking

    Check that len(s) > 0 before accessing with len(s)-1 to avoid panics on empty slices.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free