donpb2823 2012-11-20 00:29
浏览 26
已采纳

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

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条回答 默认 最新

  • donglong9745 2012-11-20 00:38
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图