Golang: Nested Slice
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
- Golang: Array
- Golang: Slice
- Golang: Slice of Slice
- Golang: Append to Slice
- Golang: Cut Slice (Delete Elements)
- Golang: Copy Slice
- Golang: Clear Slice
- Golang: Nested Slice
- Golang: Slice of Strings to String
- Golang: Iterate Slice
- Golang: Convert Value to String
- Golang: Convert Array to Slice
- Golang: Print Slice, Array