DEV Community

Ramu Mangalarapu
Ramu Mangalarapu

Posted on

1

Working with 2D slices in Golang

Have you ever passed 2D slices as function argument in Golang. 2D slice is things with slices of slices.


package main

import (
    "fmt"
)

func print2DSlice(a [][]int) {
    // let us iterate over 2D slice
    for i := 0; i < len(a); i++ {
        oD := a[i] // access 0th array in 2D slice
        for j := 0; j < len(oD); j++ {
            fmt.Printf("%d ", oD[j])
        }
        fmt.Println()
    }
    return
}

func main() {
    tDSlice := make([][]int, 0)
        // or tDSlice:=[][]int{}
    tDSlice = append(tDSlice, []int{1, 2, 3, 4, 5})
    tDSlice = append(tDSlice, []int{12, 32, 43, 423, 52})
    tDSlice = append(tDSlice, []int{2341, 322, 323, 324, 53})
    tDSlice = append(tDSlice, []int{3321, 2423, 33232, 432, 532})
    tDSlice = append(tDSlice, []int{14343, 24343, 34343, 44343, 54343})
    tDSlice = append(tDSlice, []int{14343, 24343, 3434334, 4434, 54343})
    tDSlice = append(tDSlice, []int{4343431, 43432, 34343, 44343, 4343435})

    print2DSlice(tDSlice)
}

Enter fullscreen mode Exit fullscreen mode

Ref: https://www.dotnetperls.com/2d-go
Thank you.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay