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 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置