Golang: Nested Slice

By Xah Lee. Date: .

Nested Slice

Slices can be nested. Just declare that the slots are also type slice.

var x [][]int

Declare a nested slice of int type.

package main

import "fmt"

func main() {
	var x [][]int
	fmt.Println(x) // []
}

Nested Slice with Values

var y = [][]int{{3, 4}, {7}, {1, 2}}

Declare nested slice, with initial values.

package main

import "fmt"

func main() {
	// y is slice of slice of int
	var y = [][]int{{3, 4}, {7, 8, 9}, {1, 2}}
	fmt.Println(y) // [[3 4] [7 8 9] [1 2]]
}

Create Nested Slice with make

var ns = make([][]string, 2)

Create a nested slice.

package main

import "fmt"

func main() {

	// nested slice. 2 items. each item is a slice of string
	var ns = make([][]string, 2)

	// fill the slots
	ns[0] = []string{"a", "b"}
	ns[1] = []string{"x", "y", "z"}

	fmt.Println(ns) // [[a b] [x y z]]
}

Getting and setting values.

package main

import "fmt"

func main() {

	var ss = make([][]int, 2)

	ss[0] = []int{1, 2}
	ss[1] = []int{3, 4}

	ss[1][1] = 5

	fmt.Println(ss) // [[1 2] [3 5]]
}

Golang, array and slice