0

I am trying to create a high dimension array in Golang.
Does anyone know how to do it?

e.g.

  • dims := [3,2,1] as a parameter -> want high_dims_array := make([3][2][1]int, 0)
  • dims := [2] -> want high_dims_array := make([2]int, 0)
  • dims := [3,3] -> want high_dims_array := make([3][3]int, 0)

Where the dims is a variable containing dimensions.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
En Xie
  • 510
  • 4
  • 19

2 Answers2

1

Thanks my friends. I have figured out a way to do this

func initialCube(shape []int) []interface{} {
    // base condition
    if len(shape) <= 1 {
        dim := shape[len(shape)-1]
        retObj := make([]interface{}, dim)
        for i := 0; i < dim; i++ {
            retObj[i] = 0.0
        }
        return retObj
    } else { // recursive
        dim := shape[len(shape)-1]
        retObj := make([]interface{}, dim)
        for i := 0; i < dim; i++ {
            retObj[i] = initialCube(shape[:len(shape)-1])
        }
        return retObj
    }
}
En Xie
  • 510
  • 4
  • 19
0

That looks like what dolmen-go/multidim does (it helps to allocate a slice with the required number of elements):

package main

import (
    "fmt"

    "github.com/dolmen-go/multidim"
)

func main() {
    var cube [][][]int
    multidim.Init(&cube, 8, 2, 2, 2)

    fmt.Println(cube)
}

Output:

[[[8 8] [8 8]] [[8 8] [8 8]]]

You can also use a function (still with the same library) to initialize your 3*2 slice:

package main

import (
    "fmt"

    "github.com/dolmen-go/multidim"
)

func main() {
    var a [][]int

    multidim.Init(&a, func(i, j int) int {
        return 2*i + j + 1
    }, 3, 2)

    fmt.Println(a)

    var r [][]string

    multidim.Init(&r, func(i, j int) string {
        return "foobar"[i*3+j : i*3+j+1]
    }, 2, 3)

    fmt.Println(r)
}

Output:

[[1 2] [3 4] [5 6]]
[[f o o] [b a r]]
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • thanks, but in my question dims is unkonw..which means I can't have var a [][]int at first place . the dimension is a parameter – En Xie Jul 18 '22 at 09:52
  • @EnXie you would need to iterate on your dims, and use make to make a slice of your slices. – VonC Jul 18 '22 at 11:31