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?
The Go Programming Language Specification
A primary expression of the form
a[x]
denotes the element of the array, pointer to array, slice, or string
a
indexed byx
. The valuex
is called the index,the index
x
is in range if0 <= 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