-1

In the below code:

package main

import "fmt"

func main() {

    b := make([]int, 0, 5)
    fmt.Println(len(b), cap(b), b) // 0 5

    c := b[:3]
    fmt.Println(len(c), cap(c), c) // 3 5

    d := c[1:5]
    fmt.Println(len(d), cap(d), d) // 4 4

    e := d[0:4]
    fmt.Println(len(e), cap(e), e) // 4 4

}

underlying array for d is same as underlying array for b & c

Why cap(d) is 4?

overexchange
  • 15,768
  • 30
  • 152
  • 347

1 Answers1

1

lets break it down step by step

intialized b

b := make([]int, 0, 5) // which makes [ ] = length 0, with a cap of 5

fmt.Println(len(b), cap(b), b) // 0 5

b => c

c := b[:3] // which makes [ 0 0 0 ] = length 3, still a cap of 5

fmt.Println(len(c), cap(c), c) // 3 5

c => d

d := c[1:5] // which makes [ 0 0 0 0 ] = length of 4, now with a cap of 4

fmt.Println(len(d), cap(d), d) // 4 4

the reason for c[1:5] making the cap one less because it's technically erasing c[0] from the array... it's being completely sliced out of it.

visualization

array of 5
-------------
[ 0 0 0 0 0 ]
  0 1 2 3 4

c[1:5] = [ x | 0 0 0 0 ]
           ^
           this index of the array fell behind the sliced indexs and was 
           sliced out making the new cap is based off the array [ 0 0 0 0 ]
                                                                  1 2 3 4


why didnt this happen with the others...?
-------------------------------------------
b[:3] = [ 0 0 0 | x x ]
                  ^ ^
                  these two indexs of the array did not fall behind the
                  sliced indexs which means the cap remains at 5 [ 0 0 0 x x ]
                                                                   1 2 3 4 5

gavin
  • 1,224
  • 5
  • 17