L
L
lavagod2020-03-29 12:16:02
go
lavagod, 2020-03-29 12:16:02

How is capacity formed in Golang?

Hello.

I understand Golang slowly, I got to slices. In particular, before they are "merged" (folded). I'm checking an example about merging two slices, everything works, I understand the essence. But the question is: why is the capacity not equal to the length when creating a slice? Why is it bigger and how does Golang pick it up? I have two slices, both in length = 5, and the capacity is set to them = 8. I set the length = 3 (1,2,3), the capacity was = 4. I set the length = 10, the capacity = 12.

I had an idea that the capacity is set from degree 2, but I understand that it is not. How will she pick?

package main

import "fmt"

func main() {

  var buf []int 						// buf = первый слайс
  var new []int 						// new = второй слайс
  buf = append(buf, 1,2,3,4,5) 		// buf = 1,2,3,4,5 (len=5, cap=8)
  new = append(new, 10,20,30,40,50) 	// new = 10,20,30,40,50 (len-5, cap=8)
  fmt.Println("Длина:",len(buf), "Капасити:", cap(buf), "Buf:", buf)
  fmt.Println("Длина:",len(new), "Капасити:", cap(new), "Buf:", new)
  // buf = buf + new
  buf = append(buf, new...)			// buf = buf + new
  fmt.Println("Длина:",len(buf), "Капасити:", cap(buf), "Buf:", buf)
  // buf = [1 2 3 4 5 10 20 30 40 50] (len=10, cap=16)
}


Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2020-03-29
@uvelichitel

https://golang.org/src/runtime/slice.go

func growslice(et *_type, old slice, cap int) slice {
...
    for 0 < newcap && newcap < cap {
  newcap += newcap / 4   //Вот здесь
    }
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question