Length and Capacity in Go Slices explanation

Submitted by august on Tue, 08/08/2017 - 15:47

The Capacity field is equal to the length of the underlying array, minus (the index in the array) of (the first element of the slice) (zero in this case)

type sliceHeader struct {
    ZerothElement *byte
    Length int
    Capacity int
}

var iBuffer [10]int
slice := iBuffer[0:0]

// Case 1: Underlying array has capacity of 10 byte
slice := sliceHeader{
    ZerothElement: &iBuffer[0],
    Length: 0,
    Capacity: 10,
}

// Case 2: if we slice from slice[4:], it becomes
slice := sliceHeader{
    ZerothElement: &iBuffer[4],
    Length: 0,
    Capacity: 6,
}

Since they share the same underlying array, but first element of the slice (pointing the index of underlying array) keep increasing.

Thanks @Steven Yeung's explanation

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.