Slice arrays and slices
Slice arrays and slices
Use a[low:high] to select elements from low inclusive to high exclusive. The result shares the underlying array. Omit low for zero, or high for len(a). For an array operand the upper bound is its length; for a slice operand it may extend to its capacity.
package main
import "fmt"
func main() { a := [5]int{10, 20, 30, 40, 50} s := a[1:4] fmt.Println(s, len(s), cap(s)) fmt.Println(a[:2], a[3:])}Indexes 1, 2 and 3 are included, but 4 is not. Capacity is measured from the first selected element to the end of the underlying array. The source array must be addressable when sliced.
Expected output:
[20 30 40] 3 4[10 20] [40 50]Reslice within capacity
package main
import "fmt"
func main() { a := []int{1, 2, 3, 4} s := a[1:2] t := s[:3] fmt.Println(s, len(s), cap(s)) fmt.Println(t, len(t), cap(t))}s[:3] is legal because cap(s) is 3, even though len(s) is 1. This differs from indexing s[2], which would panic. Check 0 <= low <= high <= cap(s) for an explicit two-index slice expression.
Expected output:
[2] 1 3[2 3 4] 3 3Try it locally
From [5]int{2,4,6,8,10}, select the middle three elements. Print the selection, its length and capacity. Then print its first two elements.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Slices 03: Slice arrays and slices
Check the lesson objective before moving on.
What does a[1:3] contain for a = [10,20,30,40]?
Can s[:3] work when len(s) is 1 and cap(s) is 3?