Home > Back-end >  dynamic array dimension in golang
dynamic array dimension in golang

Time:07-19

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.

CodePudding user response:

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
    }
}

CodePudding user response:

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]]
  • Related