Multidimensional Slice?

I am coding a sun position calculator in go, and the calculations use Periodic Terms which are set out in tables (see below).
I initially wanted to set them up as constants, but go does not support arrays or slices as constants.
It seems to me that a multidimensional slice may be the way to go.
The pattern I have seen to do this is as follows:
values := [][]int{}
// These are the first two rows.
row1 := []int{1, 2, 3}
row2 := []int{4, 5, 6}
// Append each row to the two-dimensional slice.
values = append(values, row1)
values = append(values, row2)

Is there 1) a better way to do this instead of using a slice and if so what is it?
2) If I have to use a multidimensional slice is there another way to build it without having to use the append() statement ( there are over 100 rows to append)



note that what you are proposing isn’t really a multidimensional slice, but rather “ragged slices” :slight_smile:
(ie: the memory locality of the elements isn’t that good.)

that said, you could do something like this:

values := [][]int{

another approach that is more memory-locality friendly:

const (
  nrows = 100
  ncols = 3

type NdArray [nrows*ncols]int
func (arr*NdArray) Get(x, y int) int {
  return (*arr)[ncols*x + y]

values := NdArray{




Thanks for the assistance. I implemented your approach and it works just fine.
As a matter of interest, when you declare NdArray like so:
type NdArray [nrows*ncols]int
how do you discern whether you are declaring an array or a slice?

It’s an array. A slice is always []something as the size is not part of its type.

1 Like

If you are not opposed to using external libraries - package tensor fills your requirement quite well.

Here’s how to do it:

a := tensor.New(tensor.Of(tensor.Int), tensor.WithShape(1,3))

for _, row := range rows {
    // convert each []int into a *tensor.Dense
    // note - this doesn't cause extra allocations.
    r := tensor.New(tensor.WithBacking(row), tensor.WithShape(1,3))
    a, _ = a.Vstack(r)

Alternatively, if you want to constraint your data to only float64, you can also use Gonum’s mat64. It has a Stack method, which works similarly.

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