Slice is an Array
Lesson 11 of 21 in Coddy's Slices and Maps in Golang course.
If you're confused about how a slice is related to an array, let's clarify. In Go, a slice is actually a reference to an array, and this array is called a "backing array." To understand this, let's consider an example:
Suppose we have a slice like this:
str := []string{"Coddy", "Learn", "Play", "test"}Do you think this str slice stores those four elements directly? The answer is no, because the slice itself doesn't directly store any elements.
What happens behind the scenes when we create a slice like that is that Go creates an array in memory and then returns a slice value that points to this array. This array is called the backing array of the slice. So, what actually stores the elements are the backing array, not the slice.
This backing array can be shared among other slices. For example:
str := []string{"Coddy", "Learn", "Play", "test"}
slice1 := str[0:3]
slice2 := str[1:4]In this example, slice1 and slice2 share the same backing array. We can notice that a slice operation doesn't create a new backing array; instead, it creates a slice that refers to some part of the same backing array.
So, in this example, all the slices share the same backing array, and we can represent this like this:
Whenever we make a change to the original slice, other slices will also reflect these changes because they are looking at the same backing array. For example, if we change "Learn" to "Fun", it will be like this:
So, you need to know that a slice literal (name := []string{}) always creates a backing array under the hood.
Try it yourself
This lesson doesn't include a code challenge.
All lessons in Slices and Maps in Golang
1Introduction
Introduction3Slices Behind the Scene
Slice is an ArraySlice with MakeCopy a SliceDelete an ElementRecap Challenge #1Recap Challenge #2