How to create a nested array or slice of slices in Go or Golang?

September 7, 2022 - 3 min read

To create a nested array or a slice of slices in Go or Golang, you can use the slice syntax but the only difference is that in the place of the type where you write the type of the slice, you have to provide another slice type that you need to hold in the slice.

TL;DR

package main

import "fmt"

func main(){
    // create a nested slice
    // made of `int` type values
    mySlice := [][]int{
        []int{1,2,3,4,5},
        []int{6,7,8,9,10},
        []int{11,12,13,14,15},
    }

    // log the nested slice to the console
    fmt.Println(mySlice); // [[1 2 3 4 5] [6 7 8 9 10] [11 12 13 14 15]] ✅
}

For example, let's say we need to make a nested slice where the nested slice should have the elements made up of the int type values.

For a simpler understanding of the nested slice, let's first create a normal slice that can hold the values that are of the int type. This is not a nested slice. We are just going to make a normal slice that can hold the int value type.

It can be done like this,

package main

func main(){
    // create a normal `int` type slice
    mySlice := []int{1,2,3,4}
}

We have now a normal slice made up of the int type values.

Now let's make this int type slice into a nested slice, where in the place of the current int values (1,2,3, and 4) in the slice we need another slice that is made of the same int type values.

So we can just replace the int with another slice of the int type.

It can be done like this,

package main

func main(){
    // create a nested slice
    // made of `int` type values
    mySlice := [][]int{}
}

Now to add values to the nested slice we can use the same syntax for creating a new int type slice inside the slice and then add the int type values. All the nested slices should also be separated by the , symbol (comma) just like normal elements in a slice.

It can be done like this,

package main

func main(){
    // create a nested slice
    // made of `int` type values
    mySlice := [][]int{
        []int{1,2,3,4,5},
        []int{6,7,8,9,10},
        []int{11,12,13,14,15},
    }
}

Let's also print the mySlice slice to the console like this,

package main

import "fmt"

func main(){
    // create a nested slice
    // made of `int` type values
    mySlice := [][]int{
        []int{1,2,3,4,5},
        []int{6,7,8,9,10},
        []int{11,12,13,14,15},
    }

    // log the nested slice to the console
    fmt.Println(mySlice); // [[1 2 3 4 5] [6 7 8 9 10] [11 12 13 14 15]] ✅
}

We have successfully made a nested slice in Go. Yay 🥳.

See the above code live in The Go Playground.

That's all 😃!

Feel free to share if you found this useful 😃.