Home > database >  Making multidimensional slice from multidimensional array does not work as expected
Making multidimensional slice from multidimensional array does not work as expected

Time:11-15

I'm trying to create a multidimensional slice from a multidimensional array and some strange things are happening (at least for me). I created a multidimensional array ma and made three slices s1, s2, s3 from it. The code below shows this:

package main

import (
    "fmt"
)

func main() {
    var ma [4][3]int32 = [4][3]int32{
        {10, 20, 30},
        {50, 60, 70},
        {80, 90, 100},
        {110, 120, 130},
    }

    var s1 [][3]int32 = ma[:]       // expected

    var s2 [][3]int32 = ma[:][:]    // ????

    var s3 [][]int32 = ma[0:2][0:2] // ????
}

var s1 [][3]int32 = ma[:] behaves as expected. ma[:] creates a slice of [3]int32 arrays, so we have an underlaying array with each element of type [3]int32 array. Tottally expected behaviour for me.

Problems arise when defining s1 and s2. It's not behaving as I expected. var s2 [][3]int32 = ma[:][:] gives the same result as var s1 [][3]int32 = ma[:]. I expected it to make a slice of slices, not a slice of arrays. How is it possible? How can the two give the same result?

Additionally, I expect var s3 [][]int32 = ma[0:2][0:2] to create a slice of slices as well. Instead it gives the error "cannot use ma[0:2][0:2] (value of type [][3]int32) as [][]int32 value in variable declaration compiler". So somehow, with ma[0:2][0:2] it gives the type [][3]int32, not [][]int32. How?

I hope I have explained what is not clear to me.

CodePudding user response:

The expression ma[:][:] parses as (ma[:])[:]. The expression evaluates to a slice expression on the result of the slice expression on ma. The outer slice expression is a noop.

Go does not have multidimensional slice expressions.

  •  Tags:  
  • go
  • Related