duanqie5741 2014-02-07 07:16
浏览 23
已采纳

整数的映射-> Go中的2d slice

I want to have a map of integers to slices with different dimensions.

var SIZE_TO_PERM = make(map[int][][]uint32, 3)

var THREE_C_THREE = [...][3]int {
    {0, 1, 2},
}

var FOUR_C_THREE = [...][3]int {
    {0, 1, 2}, {0, 1, 3}, {0, 3, 2}, {3, 1, 2},
}

var FIVE_C_THREE = [...][3]int {
    // ... etc
}

func init() {
    SIZE_TO_PERM = map[int][][]uint32 {
        3 : THREE_C_THREE,
        4 : FOUR_C_THREE,
        5 : FIVE_C_THREE,
    }
}

But this doesn't work, as Go throws errors:

# command-line-arguments
./test.go:96: cannot use THREE_C_THREE (type [1][5]int) as type [][]uint32 in map value
./test.go:97: cannot use FOUR_C_THREE (type [4][5]int) as type [][]uint32 in map value
./test.go:98: cannot use FIVE_C_THREE (type [20][5]int) as type [][]uint32 in map value

How can I get around this? Perhaps I could somehow have Go map an int to a pointer/reference to a map? Then all the types would be the same, I'd just have to follow the address to get the map there. The problem is I wouldn't know apriori which type I'd find there...

All new to Go, so any tips appreciated.

  • 写回答

1条回答 默认 最新

  • dongmou9260 2014-02-07 07:53
    关注

    First of all, there is a difference between a slice and an array.

    var a [3]int // Array of 3 ints
    var s []int // Slice of ints
    

    In your case, the map can store slices, but the data is stored in different types of arrays.

    The size of an array is part of its type. And because of Go's strict typing, you cannot set a value of one array type/size to a value of a different array type/size.

    Instead we have slices. Slices uses an underlying array, but may differ in length and capacity.

    You can solve your problem by changing your code:

    var THREE_C_THREE = [][]uint32 { // Changed type from [1][3]int to [][]uint32
        {0, 1, 2},
    }
    
    var FOUR_C_THREE = [][]uint32 { // Changed type from [4][3]int to [][]uint32
        {0, 1, 2}, {0, 1, 3}, {0, 3, 2}, {3, 1, 2},
    }
    
    var FIVE_C_THREE = [][]uint32 { // Changed type from [5][3]int to [][]uint32
        // ... etc
    }
    

    This official blog-post will give you more info: http://blog.golang.org/slices
    And this post as well: http://blog.golang.org/go-slices-usage-and-internals

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条