duanqie5741
duanqie5741
2014-02-07 07:16

整数的映射-> 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 dongmou9260 7年前

    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

    点赞 评论 复制链接分享

相关推荐