Slicing itself is not a dynamic array or array pointer. It internally references the underlying array with Pointers and sets properties to restrict data reads and writes to the specified region. The concept of slicing in Go is similar to, but not as flexible as, the concept of slicing in Python.

Slices can be created based on an array or array pointer to determine the referenced array fragment with the starting and ending index positions. Reverse indexes are not supported, and the actual range is a right half open range.

Create slices by arR [begin:end]. Where arR is an array that will already be created. Begin is the starting index position of slice, which can be omitted. End is the end of the slice index. The slice data does not include elements on the index. End can also be omitted, which indicates the length of the array.

package main
import "fmt"

func main(a) {
    s := [...]int{0.1.2.3.4.5.6.7.8.9}
    s1 := s[:] // equivalent to s[0:10]
    fmt.Println(s1) // [0 1 2 3 4 5 6 7 8 9]

    s2 := s[1:6]
    fmt.Println(s2) // [1 2 3 4 5]

    s3 := s[4:] // equivalent to s[4:10]
    fmt.Println(s3) // [4 5 6 7 8 9]

    s4 := s[:8] // equivalent to s[0:8]
    fmt.Println(s4) // [0 1 2 3 4 5 6 7]
}
Copy the code

The above code defines an array of type int of length 10. A full slice S1 was obtained by means of S [:].

Like arrays, slicing uses subscripts to access element content. The subscript is 0, but not the actual subscript position of the underlying array.

package main
import "fmt"

func main(a) {
    s := [...]int{0.1.2.3.4.5.6.7.8.9}
    s1 := s[4:]

    for i:=0; i<len(s1); i++ {
            fmt.Printf("%d ", s1[i])
    }
    
    // Output 4 5 6 7 8 9
}
Copy the code