'How do I take a set of arrays (strings) and create a multidimensional slice of those arrays in Golang?
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 1:[1]
Couldn't one just say something like
func bundleSlices( slices ...[]int) [][]int {
return slices
}
And then:
package main
import "fmt"
func main() {
arr1 := []int{1, 2, 3}
arr2 := []int{4, 5, 6}
arr3 := []int{7, 8, 9}
bundled := bundleSlices( arr1, arr2, arr3 )
fmt.Println(bundled)
}
to get
[[1 2 3] [4 5 6] [7 8 9]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicholas Carey |
