Capacity of schools in Golang

Asked

Viewed 221 times

4

One Slice can vary with the need and can add items to it, right? It is possible to view the size and its capacity (len and cap, respectively).

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

How the capacity of Slices in Go? How 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)
}

1 answer

3


A Slice is composed of 3 members:

  • the address where it should start, which should be within a array in memory, that is, it is a pointer
  • size so he knows where it ends, it’s an integer
  • the capacity of the slice which is also an integer.

If the Slice is not done on top of a array, a will be created. A common mistake is to think that it is already a array. Are separate things.

Capacity is how many elements can be used in array that is taking a slice. When the capacity is not enough it is necessary to recreate the array more capable.

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

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

  • "It doubles the capacity" It’s not quite so. The way the slice grows depends so much on the capacity of the slice how many elements will be added. For those who are curious, here is the function that coordinates Slice growth.

  • @Felipemarinho is, I don’t remember if I got confused, or was like that and already changed. I was going to say that this is implementation detail and forgot, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.