Contenido del Curso
Introduction to GoLang
Introduction to GoLang
Length vs Capacity
We can determine the length of an array or a slice using the len
function:
index
randomNumbers := [] int { 1, 4, 5, 7, 9, 10, 12 } fmt.Println(len(randomNumbers)) // Output: 7 numbersSlice := randomNumbers[2:7] fmt.Println(len(numbersSlice)) // Output: 5
We can determine the capacity of an array or a slice using the cap
function:
The length and capacity of an array are always the same. However, for a slice, the capacity might differ from the length. For instance, in the case where a slice is created from an array, the capacity is greater than the length:
index
randomNumbers := [7] int { 1, 4, 5, 7, 9, 10, 12 } numbersSlice := randomNumbers[1:3] fmt.Println(len(numbersSlice)) // Output: 2 fmt.Println(cap(numbersSlice)) // Output: 6
The capacity of a slice is the number of elements from the startingIndex
of the slice to the end of the original array from which it was created. In the example above, it is 6
.
Remember that modifying a slice also modifies the original array. Therefore, in the given example, appending an element (or value) to a slice essentially updates the element next to the slice's ending index in the original array. In other words, it increases the size of the slice and updates the elements of the original array based on the appended elements/values. This will become clearer with an example:
index
randomNumbers := [7] int { 1, 4, 5, 7, 9, 10, 12 } numbersSlice := randomNumbers[1:3] fmt.Println(randomNumbers) // Output: [1 4 5 7 9 10 12] numbersSlice = append(numbersSlice, 20, 30, 40) fmt.Println(randomNumbers) // Output: [1 4 5 20 30 40 12]
The capacity is useful for determining how many elements we can append to the slice. If we exceed the capacity of the slice, the append
function creates and returns a new slice that is not connected to a portion of the original array. Therefore, it becomes detached from the original array.
You can see the following example: the original array remains unchanged even though we appended more elements to its slice:
index
numbers := [] int { 1, 2, 3, 4 } numSlice := numbers[1:3] fmt.Println(numbers) // Outputs: [1 2 3 4] fmt.Println(numSlice) // Outputs: [2 3] fmt.Println(cap(numSlice)) // Outputs: 3 numSlice = append(numSlice, 9, 10) fmt.Println(numSlice) // Outputs: [2 3 9 10] fmt.Println(numbers) // Outputs: [1 2 3 4]
This happened because the slice had a capacity of 3, which we exceeded. As a result, the append
function returned a new slice that no longer references the original array.
¡Gracias por tus comentarios!