Golang 'index out of range' Error: Understanding and Fixing It
This error occurs when you attempt to access an element in a slice or array that exceeds its defined length. For instance, if you have a slice with a length of 2 and try to retrieve the element at index 2, you'll encounter this error.
To resolve this, ensure you are accessing elements within the boundaries of the slice or array. Utilize the built-in len() function to determine the length of a slice or array before accessing its elements.
For example, with a slice 's' having a length of 2, you can access its elements at indices 0 and 1 like this:
s := []int{1, 2}
fmt.Println(s[0]) // Output: 1
fmt.Println(s[1]) // Output: 2
If you try to access the element at index 2, you'll receive an 'index out of range' error:
fmt.Println(s[2]) // Error: index out of range [2] with length 2
原文地址: https://www.cveoy.top/t/topic/lDKK 著作权归作者所有。请勿转载和采集!