How to Create and Print Multi Dimensional Slice in Golang?

Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, but the size of the slice is resized they are not in fixed-size just like an array. Internally, slice and an array are connected with each other, a slice is a reference to an underlying array. It is allowed to store duplicate elements in the slice. The first index position in a slice is always 0 and the last one will be (length of slice – 1).

Multi-dimensional slice is just like the multidimensional array, except that slice does not contain the size.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// the multi-dimensional slice
package main
  
import "fmt"
  
func main() {
  
    // Creating multi-dimensional slice
    s1 := [][]int{
        {1, 2},
        {3, 4},
        {5, 6},
        {7, 8},
    }
  
    // Accessing multi-dimensional slice
    fmt.Println("Slice 1 : ", s1)
  
    // Creating multi-dimensional slice
    s2 := [][]string{
        []string{"str1", "str2"},
        []string{"str3", "str4"},
        []string{"str5", "str6"},
    }
  
    // Accessing multi-dimensional slice
    fmt.Println("Slice 2 : ", s2)
  
    // Printing every slice inside s2
    fmt.Println("MultiDimensional Slice s2:")
    for i := 0; i < len(s2); i++ {
        fmt.Println(s2[i])
    }
  
    // Printing elements in slice as matrix
    fmt.Println("Slice s2 Like Matrix:")
  
    // number of rows in s2
    n := len(s2)
  
    // number of columns in s2
    m := len(s2[0])
    for i := 0; i < n; i++ {
        for j := 0; j < m; j++ {
            fmt.Print(s2[i][j] + " ")
        }
        fmt.Print("\n")
    }
}

chevron_right


Output:

Slice 1 :  [[1 2] [3 4] [5 6] [7 8]]
Slice 2 :  [[str1 str2] [str3 str4] [str5 str6]]
MultiDimensional Slice s2:
[str1 str2]
[str3 str4]
[str5 str6]
Slice s2 Like Matrix:
str1 str2 
str3 str4 
str5 str6 



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.