Go:使用现有数组的类型和值定义多维数组?

huangapple go评论87阅读模式
英文:

Go: Define multidimensional array with existing array's type and values?

问题

可以使用现有数组来定义和初始化一个新的多维数组吗?就像下面的代码中,而不是使用<code>var b [2][3]int</code>,只是像<code>var b [2]a</code>这样说?使用a的类型,无论它是什么,而不是硬编码它(这样会错过使用[...]的意义)。同时处理初始化=复制值的问题?

package main

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

(我知道切片的简便性和方便性,但这个问题是关于理解数组的。)

编辑:我不敢相信我忘记了<code>var b [2][len(a)]int</code>,初学者的脑袋冻结。一行答案是<code>var b = [2][len(a)]int{a,a}</code>。那是一种类型转换,对吗?

英文:

Is it possible to a)define b)initialize a new multidimensional array using an existing array, like in following code instead of <code>var b [2][3]int</code>, just saying something like <code>var b [2]a</code> ?<br>
Using a's type whatever it is, instead of hardcoding it (which misses the point of using [...] for a).<br>
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 <code>var b [2][len(a)]int</code>, beginner's brain freeze. One line answer would be <code>var b = [2][len(a)]int{a,a}</code> . That's a type conversion, right?

答案1

得分: 5

以下代码也可以工作。你的例子和我的例子都做了同样的事情,两者之间的速度应该没有太大差异。

除非你使用反射(reflect)来创建一个你的[3]int的切片(slice)(而不是数组),否则在你的新类型中不重复[3]int是不可能的。即使在当前版本中也不可能。在Go 1.1中将会发布。

package main

import "fmt"

func main() {
    a := [...]int{4,5,6}
    var b = [2][3]int{a, a}
	fmt.Println(b)
}
英文:

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 &quot;fmt&quot;

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

huangapple
  • 本文由 发表于 2012年11月20日 08:29:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/13464838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定