4

Is it possible to a)define b)initialize a new multidimensional array using an existing array, like in following code instead of var b [2][3]int, just saying something like var b [2]a ?
Using a's type whatever it is, instead of hardcoding it (which misses the point of using [...] for a).
And perhaps handling initialization=copying of 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'm aware of ease and convenience of slices, but this question is about understanding arrays.)

Edit: can't believe I forgot about var b [2][len(a)]int, beginner's brain freeze. One line answer would be var b = [2][len(a)]int{a,a} . That's a type conversion, right?

1
  • maybe Templates since they can support any type Commented Nov 20, 2012 at 0:34

1 Answer 1

5

The following code would also work. Both your example and mine do the same thing and neither should be much faster than the other.

Unless you use reflect to make a slice (not array) of your [3]int, it is impossible to not repeat [3]int in your new type. Even that is not possible in the current release. It is in 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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I also seem to have a beginner's brain freeze, as var b [2][len(a)]int seems to work just fine.
Yes, len(array) is a constant expression (calculated at compile time) and therefore can be used when defining other array types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.