You get a sub-slice in Go by using slice slicing syntax slice[low:high], which creates a new slice header pointing to the same underlying array as the original. Remember that this is a shallow copy; the new slice shares the underlying data, so modifying elements in the sub-slice affects the original slice.
Here is the basic syntax for extracting a range:
numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
// Get elements from index 2 up to (but not including) index 5
sub := numbers[2:5]
fmt.Println(sub) // Output: [2 3 4]
You can omit the start index to begin from the beginning, or the end index to go to the end of the slice. Be careful with bounds; if low or high are out of range, Go will panic at runtime.
// From index 3 to the end
rest := numbers[3:]
// From the beginning to index 4
firstFour := numbers[:4]
// Empty slice if low == high
empty := numbers[2:2]
A critical detail is that slicing does not copy the data. If you modify an element in the sub-slice, the change reflects in the original slice because they share the same backing array. If you need an independent copy of the data, you must explicitly allocate a new slice and copy the contents.
original := []int{10, 20, 30, 40, 50}
sub := original[1:3] // [20, 30]
sub[0] = 999
fmt.Println(original) // Output: [10 999 30 40 50] - original is modified!
// To avoid this, copy the data:
independent := make([]int, len(sub))
copy(independent, sub)
independent[0] = 123
fmt.Println(original) // Output: [10 999 30 40 50] - original unchanged
Also, be aware of the capacity. A sub-slice's capacity extends to the end of the original underlying array, not just the end of the sub-slice range. This means you can append to a sub-slice, but it might overwrite data in the original slice that comes after the sub-slice range if the capacity allows it.
nums := []int{1, 2, 3, 4, 5}
sub := nums[1:2] // [2], capacity is 4 (indices 1 to 5)
sub = append(sub, 99)
// Result: nums is now [1, 2, 99, 4, 5] - the 3 was overwritten!
If you need to safely append to a sub-slice without affecting the rest of the original data, use make to create a new slice with the copied data first, then append to that.