U
U
uvelichitel2019-01-18 19:09:46
go
uvelichitel, 2019-01-18 19:09:46

How to dynamically allocate array [var]type?

Obviously it doesn't compile.

length := 7
var array [length]int

Compiling
const length = 7
var array [length]int
//or
length := 7
slice := make([]int, length)  //we get a slice here instead of array

In the second case, we get a slice, not an array. And I want exactly an array, for example, to control allocation, reduce pressure on the GarbageCollector (well, or for other reasons, you never know, it’s not in vain that the array type is defined in the language). And I want to allocate this array dynamically.
use cases
func UseArray(length int){
    var array //of length  ???????
    for _, value := range array{  //do something with array
        fmt.Println(value)
    }
}

Here is a blank on the playground to play with the answers .
I tried with unsafe and reflect and it seems that I got something similar to the solution. But the code is so miserable, angular and dependent on the implementation of unsafe in the compiler that it is even a shame to show it. In general, the Orthodox solution using unsafe and reflect is quite satisfactory.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
rustler2000, 2019-01-18
@uvelichitel

In any way - for escape analysis your array all the same can put in hip.
```
package main
import (
"fmt"
)
func z(i int) {
var s [10]int
for n := 0; n<i; n++ {
s[n] = n
}
fmt.Printf("%v", s)
}
func main() {
z(10)
}
```
```
$ go build -gcflags="-m" main.go
# command-line-arguments
./main.go:12:12: z ... argument does not escape
```

V
Vladislav, 2019-01-18
@ghostiam

Slices use the same arrays under the hood.
Using:

length := 7
slice := make([]int, length)

a slice is allocated, yes, but it is exactly the length that was specified, just like an array. https://play.golang.org/p/vAQqLI-msfi

R
Roman Kitaev, 2019-01-18
@deliro

to control allocation for example

Create a slice with more capability, what's the problem?
https://play.golang.org/p/kyM2gbCmyGW

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question