How do I take a set of arrays (strings) and create a multidimensional slice of those arrays in Golang?

Issue

I am trying to implement a function, that when passed an array of strings, it creates a slice of arrays, and adds to it every array that is passed. It would return the final slice of all arrays that was passed.

Just as a test, I initialized 4 arrays and tried to create a function that would do just this. However, it fails quite miserably. This is what I have so far. Not sure how to go about this.

func main() {
    array1 := []string{"x", "o", "x", "_", "_"}
    array2 := []string{"0", "o", "x", "_", "_"}
    array3 := []string{"o", "o", "o", "_", "_"}
    array4 := []string{"o", "o", "o", "o", "o"}

    FinalSlice(array1)
    FinalSlice(array2)
    FinalSlice(array3)
    fmt.Println(FinalSlice(array4))

}

func FinalSlice(array []string) [][]string {
    var slice [][]string
    for i, _ := range slice {
        slice[i] = array
    }
    return slice

}

Right now this is the output:

[]

Solution

That is because you loop through an empty slice, which has no elements.

So your loop

for i, _ := range slice {}

will actually run 0 iteration (that’s why you end up with an empty array).

I don’t understand the exact result you want to achieve, but if you want to concat arrays into a multi-dimensional one, you can use the below code:

package main

import "fmt"

func AppendSlice(source [][]string, value []string) [][]string {
    return append(source, value)
}

func main() {
    array1 := []string{"x", "o", "x", "_", "_"}
    array2 := []string{"0", "o", "x", "_", "_"}
    array3 := []string{"o", "o", "o", "_", "_"}
    array4 := []string{"o", "o", "o", "o", "o"}

    var finalArray [][]string

    finalArray = AppendSlice(finalArray, array1)
    finalArray = AppendSlice(finalArray, array2)
    finalArray = AppendSlice(finalArray, array3)
    finalArray = AppendSlice(finalArray, array4)

    // [[x o x _ _] [0 o x _ _] [o o o _ _] [o o o o o]]
    fmt.Println(finalArray) 
}

This may be improved in many ways, feel free to play around with this solution: https://go.dev/play/p/vXvqlRZuOUI

Answered By – KawaLo

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.