golang slice, slicing a slice with slice[a:b:c]
The syntax has been introduced in Go 1.2, as I mentioned in "Re-slicing slices in Golang".
It is documented in Full slice expressions:
a[low : high : max]
constructs a slice of the same type, and with the same length and elements as the simple slice expression
a[low : high]
.
Additionally, it controls the resulting slice's capacity by setting it tomax - low
.
Only the first index may be omitted; it defaults to 0.After slicing the array
a
:
a := [5]int{1, 2, 3, 4, 5}
t := a[1:3:5]
the slice t has type []int, length 2, capacity 4, and elements
t[0] == 2
t[1] == 3
The design document for that feature had the following justification:
It would occasionally be useful, for example in custom
[]byte
allocation managers, to be able to hand a slice to a caller and know that the caller cannot edit values beyond a given subrange of the true array.The addition of
append
to the language made this somewhat more important, becauseappend
lets programmers overwrite entries betweenlen
andcap
without realizing it or even mentioningcap
.
It is explained well in Go release notes. Please note a missing first index ([:0:0]) defaults to zero.