Understand the contract
A slice describes a segment of an underlying array. It has a length, a capacity and a reference to storage. Assigning a slice copies that description, so two slices can refer to the same elements. This is why changing an element through a subslice can change the original sequence.
len reports the number of elements currently accessible. cap reports how far the slice can extend through its backing array. The expression values[1:3] includes indices one and two and excludes index three. Bounds must be valid; slicing does not silently clamp an invalid boundary.
Work through the example
The example first changes the shared element to 99. It then allocates a new slice and copies the values into it. Changing independent[0] to seven leaves values unchanged. make creates the destination length, while copy returns the number of elements copied, limited by the shorter slice.
package main
import "fmt"
func main() {
values := []int{10, 20, 30}
window := values[1:]
window[0] = 99
independent := make([]int, len(values))
copy(independent, values)
independent[0] = 7
fmt.Println(values, independent)
}Watch this boundary
A nil slice has length and capacity zero and can be appended to. It differs from a non-nil empty slice in some representations, including JSON null versus an empty array. Choose an API representation deliberately rather than treating the two as identical in every context.
Practice with a changed input
Print len and cap for the original slice and its subslice. Copy into a destination of length one and observe the returned count and the untouched source.
Lesson 13 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services