Cast 2D array to 2D slice

Hi,

I’m sure it’s been asked umpteen times before but I feel I must be missing something.
I’m trying to use writeAll, which expects a 2D slice of strings.
Unfortunately, my object is a 2D array. I tried to cast it to a slice with M[:][:] but the second dimension is still an array:
cannot use m[:][:] (type [][12]string) as type [][]string in argument to w.WriteAll

Is there some syntactic sugar I can try to make it work? I’d rather avoid building a slice just for that.

Example: Go Playground - The Go Programming Language

Thank you!

Conver your array to slice. For example

func array2Slice(m [8][12]string) string {
slice := make(string, len(m))
for r := 0; r < len(m); r++ {
cols := make(string, len(m[r]))
for c := 0; c < len(m[r]); c++ {
cols[c] = m[r][c]
}
slice[r] = cols
}
return slice
}

To use in your code, just

slice := array2Slice(m)
w := csv.NewWriter(os.Stdout)
w.WriteAll(slice)

Thank you for the reply but that’s what I wanted to avoid. If it were a 1D array, using [:] would turn it into a slice without any helper function. I’m wondering if there’s a way to that for a 2D array, without resorting to explicitly building and populating a 2D slice.

I resorted to make a 2D slice, similar to the proposed solution but without copying the values.

func arrayAsSlice(m *[8][12]string) [][]string {
	s := make([][]string, len(m))
	for r := 0; r < len(m); r++ {
		s[r] = m[r][:]
	}
	return s
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.