Gaaker Go

Golang Initialize slice

A slice reference to a continuous segment of an array. the expression.

var slice1 []type = array1[start:end]

slice1 is a subset of the elements of array1 indexed from start to end-1.

Slices can also be initialized in a manner similar to arrays.

The following example creates an array of length 5 and creates a related slice.

var slice2 = []int{2, 3, 5, 7, 11}

The following is a complete code example.

package main

import "fmt"

func main() {
	var arr1 = [6]int {0,1,2,3,4,5}
	var slice1 []int = arr1[2:5] // item at index 5 not included!
	fmt.Println(slice1)

	var slice2 = []int{2, 3, 5, 7, 11}
	fmt.Println(slice2)
}

Below is the program output:

[2 3 4]
[2 3 5 7 11]
< Initialize slice Initialize slice >