如何在golang中找到(2,3或可能的话n)维切片的尺寸并验证其是否为矩阵?

For example : [][]float64{{11, 5, 14, 1}, {11, 5, 14, 1}} has dimensions [2,4].

If this is passed to a function then what is the most efficient way to find the dimension here?

Thanks

The outer dimension is just len(x) where x is the slice of slices you pass to the function (your example [][]float64{{11, 5, 14, 1}, {11, 5, 14, 1}}). However, the inner dimensions are not guaranteed to be equal so you will have to go through each element and check what len they have.

If you have the guarantee than each element of x has the same number of elements, just find len(x[0]) if len(x) > 0.

Go only provides 1-dimensional arrays and slices. N-dimensional arrays can be emulated by using arrays of arrays, which is close to what what you're doing--you have a 1-dimensional slice, which contains 2 1-dimensional slices.

This is problematic, because slices are not of a defined length. So you could end up with slices of wildly different lengths:

[][]float64{
    {1, 2, 3, 4},
    {5, 6, 7, 8, 9, 10},
}

If you use actual arrays, this is simpler, because arrays have a fixed length:

[2][4]float64

You can extend this to as many dimensions as you want:

[2][4][8]float64 provides three dimensions, with respective depths of 2, 4, and 8.

Then you can tell the capacity of each dimension by using the built-in len() function on any of the elements:

foo := [2][4][7]float64{}
x := len(foo)       // x == 2
y := len(foo[0])    // y == 4
z := len(foo[0][0]) // z == 8