Home > Article > Backend Development > Why Does My Go Code Throw a \"panic: runtime error: index out of range\" Error When the Array Length is Not Null?
"Go “panic: runtime error: index out of range” When the Length of Array is Not Null
Analysis
The provided Go code encounters a runtime error due to accessing an index beyond the allowed range. When working with slices in Go, it's crucial to understand the concept of capacity and length.
Understanding Slices
A Go slice is a descriptor of an array segment. It encompasses a pointer to the array, the length of the segment, and its capacity (maximum length of the segment).
make([]string, 0, 4) vs. make([]string, 4)
The make function initializes and allocates slices. result := make([]string, 0, 4) creates a slice with length 0 and capacity 4, while result := make([]string, 4) (or its equivalent result := []string{"", "", "", ""}) initializes a slice with both length and capacity 4.
Array Access
In result := make([]string, 0, 4), the underlying array is empty, so accessing result[0] will cause a runtime error. In contrast, result := make([]string, 4) has four string elements, allowing access to result[0], result[1], result[2], and result[3].
Resolution for Your Code
In your myFunc function, you use the problematic result := make([]string, 0, 4) initialization. Given that your code requires appending elements, you should consider using result := make([]string, 0) and append elements using the append function. Alternatively, you could use result := []string{} or result := make([]string, 4), depending on your specific requirements.
Here's a working version of your code using make([]string, 0) and append (The Go Playground):
<code class="go">package main import "fmt" func main() { fmt.Println(myFunc("Political srt")) } func myFunc(input string) []string { strs := strings.Fields(input) result := make([]string, 0) // Initialize with length 0 and append as needed for _, s := range strs { if strings.ContainsAny(s, "eaiu") { result = append(result, s) // Append to the result slice } } return result }</code>
The above is the detailed content of Why Does My Go Code Throw a \"panic: runtime error: index out of range\" Error When the Array Length is Not Null?. For more information, please follow other related articles on the PHP Chinese website!