Connection Between Slices and Arrays

Let’s learn how slices are connected to arrays.

How slices are connected to arrays

As mentioned before, behind the scenes, each slice is implemented using an underlying array. The length of the underlying array is the same as the capacity of the slice, and there exist pointers that connect the slice elements to the appropriate array elements.

We can understand that by connecting an existing array with a slice, Go allows us to reference an array or a part of an array using a slice. This has some strange capabilities, including the fact that the changes to the slice affect the referenced array! However, when the capacity of the slice changes, the connection to the array ceases to exist! This happens because when the capacity of a slice changes, so does the underlying array, and the connection between the slice and the original array does not exist anymore.

Coding example

We will now look at the code of sliceArrays.go to understand how slices are connected to arrays.

Get hands-on with 1200+ tech skills courses.