Why does one of my two slices panic with "runtime error: index out of range"?
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*
}
为什么 fmt.Println(str2[0])
在 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 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{}
与 make([]string, 0)
相同,因此,0 >= len(str2)
和 str2[0]
超出范围..
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*
}
游乐场:https://play.golang.org/p/p31fUyb4pqW
输出:
10 10 [ ]
0 0 []
panic: runtime error: index out of range [0] with length 0
func main() {
str1 := make([]string, 10)
str2 := []string{}
fmt.Println(str1[0]) *No error*
fmt.Println(str2[0]) *error*
}
为什么 fmt.Println(str2[0])
在 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{}
与 make([]string, 0)
相同,因此,0 >= len(str2)
和 str2[0]
超出范围..
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*
}
游乐场:https://play.golang.org/p/p31fUyb4pqW
输出:
10 10 [ ]
0 0 []
panic: runtime error: index out of range [0] with length 0