Go to: Define a multidimensional array with existing array type and values?

Is it possible a) to define b) to initialize a new multidimensional array using the existing array, as in the following code instead of var b [2][3]int , just saying something like var b [2]a ?
Using the type, whatever it may be, instead of hard coding (which skips the point of use [...] for a).
And perhaps initialization processing = copying values ​​at the same time?

 package main func main () { a := [...]int{4,5,6} var b [2][3]int b[0],b[1] = a,a } 

(I know the ease and convenience of slicing, but this question is about understanding arrays.)

Edit: I can't believe I forgot about var b [2][len(a)]int , freezing the brains of beginners. One answer would be var b = [2][len(a)]int{a,a} . What type conversion is right?

+4
source share
1 answer

The following code will also work. Both your example and mine do the same, and none of them should be much faster than the other.

If you do not use reflex to create a fragment (not an array) of your [3]int , it is impossible to repeat [3]int in a new type. Even this is not possible in the current release. It is at the tip and will be released in Go 1.1.

 package main import "fmt" func main() { a := [...]int{4,5,6} var b = [2][3]int{a, a} fmt.Println(b) } 
+5
source

Source: https://habr.com/ru/post/1447111/


All Articles