Go Slice Error: panic:runtime error:index out of range [0] with length 0 [Solved]

Problem source: as shown in the figure below, I declare a slice that prompts me that the subscript is out of bounds


let’s debug why this happens

we can see that the slice in this declaration mode stores not zero values, but nil
in fact, we just need to change it to var SS = make ([] int, n)
next, let’s look at the principle and deeply analyze the three special state zero slices of go language slice, Empty slice and nil slice
the bottom layer of slice is an array, and the surface layer of slice is a structure containing three variables. When we assign a slice to another slice, it is essentially a shallow copy of the surface structure of slice. The first variable in the structure is a pointer to the underlying array, and the other two variables are the length and capacity of the slice

let’s first look at the simplest zero slice

then empty slice and nil slice

the above four forms seem to be the same from the output results. But in fact, there are differences. The two special types of “empty slice” and “nil slice” we want to talk about are hidden in the above four forms. How can we analyze the differences between the internal structures of three sides and four forms?Next, we will use the high-level content of go language to convert any variable type of go language through unsafe. Pointer. Because the internal structure of the slice is a structure body, which contains three machine word size integer variables. The first variable is a pointer variable, and the pointer variable also stores an integer value, but this value is the memory address of another variable. We can look at this structure as an integer array [3] int with a growth of 3. Then convert the slice variable to [3] int

from the output, we see obvious, magical, surprising and incomprehensible different results. The S1 and S4 variables whose output is [0] are “nil slices”, and the S2 and S3 variables are “empty slices”. 824634199592 this value is a special memory address shared by all types of “empty slices”


the last question is: is there any difference between “nil slice” and “empty slice”?The official recommends nil slices. See why

“empty slice” and “nil slice” are sometimes hidden in the structure. At this time, their differences are ignored by too many people. Let’s take an example

it can be found that the results of creating structures are different between the two types! ” Another great difference between “empty slice” and “nil slice” is JSON serialization, which is extremely important


Read More: