Search code examples
goruntime-errorindexoutofrangeexceptionpanic

Why does one of my two slices panic with "runtime error: index out of range"?


func main() {
        str1 := make([]string, 10)
        str2 := []string{}
        fmt.Println(str1[0]) *No error*
        fmt.Println(str2[0]) *error*
    }

Why does fmt.Println(str2[0]) show an error in Go?


Solution

  • The Go Programming Language Specification

    Index expressions

    A primary expression of the form

    a[x]
    

    denotes the element of the array, pointer to array, slice, or string a indexed by x. The value x is called the index,

    the index x is in range if 0 <= x < len(a), otherwise it is out of range


    []string{} is the same as make([]string, 0) Therefore, 0 >= len(str2) and str2[0] is out of range..

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        str1 := make([]string, 10)
        fmt.Println(len(str1), cap(str1), str1)
        str2 := []string{}
        fmt.Println(len(str2), cap(str2), str2)
        fmt.Println(str1[0]) // *No error*
        fmt.Println(str2[0]) // *error*
    }
    

    Playground: https://play.golang.org/p/p31fUyb4pqW

    Output:

    10 10 [         ]
    0 0 []
    
    panic: runtime error: index out of range [0] with length 0