Slag capacity in Golang

4

A slice can vary with need, and you can add items to it, right? You can view the size and its capacity ( len and cap , respectively).

On the tour by Go, there is a "lesson" from append , it first creates a slice null and then adds a 0 to it and the size becomes 1 and the capacity becomes 2. In the last append , it adds "2, 3, 4" to slice which already had 2 size and 2 capacity, and gets 5 capacity size of 8.

How does the ability of slices in Go? What is the "growth" of slices ?

Here is the code:

package main

import "fmt"

func main() {
    s := []int{2, 3, 5, 7, 11, 13}
    printSlice(s)

    // Slice the slice to give it zero length.
    printSlice(s[:0])

    // Extend its length
    printSlice(s[:4])

    // Drop its first two values.
    printSlice(s[2:])
}

func printSlice(s []int) {
    fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
    
asked by anonymous 12.12.2017 / 20:49

1 answer

3

A slice is made up of 3 members:

  • the address where it should start, which must be inside an array in memory, ie it is a pointer
  • The size so it knows where it ends, is an integer
  • the capacity of the slice which is also an integer.

If slice is not done over an array , one will be created. A common mistake is to assume that it is already an array . They are different things.

Capacity is how many elements you can use in the array that is taking a slice. When the capacity is not sufficient you need to recreate the array with more capacity.

You can do it manually or you can use the append() ready function that does for you. The algorithm varies and this is implementation detail, do not count it will grow in a specific way, if you need it do your own algorithm. A current implementation .

There is a reallocation of memory, which can be expensive in large volumes. So the ideal is to already have a slice array ) with the exact size or close to what you need to use. For small volumes it changes very little.

    
12.12.2017 / 21:53