How to Create and Print Multi Dimensional Slice in Golang?


A slice is a dynamically-sized array in Go. It is an essential data structure for any Go program. Multi-dimensional slices, as the name suggests, are slices with more than one dimension. In this article, we will learn how to create and print a multi-dimensional slice in Go.

Creating a Multi-Dimensional Slice

To create a multi-dimensional slice in Go, we can simply define a slice of slices.

Example

Here's an example −

package main

import "fmt"

func main() {
   // Creating a 2D slice
   a := [][]int{{1, 2}, {3, 4}, {5, 6}}

   // Creating a 3D slice
   b := [][][]int{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}

   // Printing the slices
   fmt.Println(a)
   fmt.Println(b)
}

Output

[[1 2] [3 4] [5 6]]
[[[1 2] [3 4]] [[5 6] [7 8]]]

In the above code, we have created a 2D slice a and a 3D slice b. The a slice has 3 rows and 2 columns, and the b slice has 2 rows, 2 columns, and 2 depths. We have used a struct literal to initialize the slices with values.

Printing a Multi-Dimensional Slice

To print a multi-dimensional slice in Go, we can use loops.

Example

Here's an example −

package main

import "fmt"

func main() {
   // Creating a 2D slice
   a := [][]int{{1, 2}, {3, 4}, {5, 6}}

   // Printing the 2D slice
   for i := 0; i < len(a); i++ {
      for j := 0; j < len(a[i]); j++ {
         fmt.Print(a[i][j], " ")
      }
      fmt.Println()
   }
}

Output

1 2 
3 4 
5 6

In the above code, we have created a 2D slice a. We have used nested for loops to print each element of the slice. The outer loop iterates through the rows, and the inner loop iterates through the columns.

Conclusion

Multi-dimensional slices are an important data structure in Go. We can create them by defining a slice of slices. We can print them using loops. By mastering multi-dimensional slices, we can write more powerful and efficient Go programs.

Updated on: 05-May-2023

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements