Slice of an array


We can use the array[start:end] syntax to get a slice of the array. The returned object is called a slice and it is a window onto the underlying array. It has a length defined by the start and end of the slice. It also has a capacity, which is all the places in the array from the start of the sliced to the end of the array.

examples/slice-of-array/slice_of_array.go
package main

import (
    "fmt"
)

func main() {
    planets := [...]string{"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn"}

    fmt.Println(planets)
    fmt.Println(len(planets))
    fmt.Println(cap(planets))
    fmt.Printf("%T\n", planets)

    part := planets[1:4]
    fmt.Println(part)
    fmt.Println(len(part))
    fmt.Println(cap(part))
    fmt.Printf("%T\n", part)
}

[Mercury Venus Earth Mars Jupiter Saturn]
6
6
[6]string
[Venus Earth Mars]
3
5
[]string