donglian3061 2016-06-18 19:10
浏览 141
已采纳

为什么不能将Go slice用作Go映射中的键,就像将数组用作键一样?

Why can't Go slice (which is an implementation of Go arrays) be used as keys in Go maps pretty much the same way arrays can be used as keys?

  • 写回答

2条回答 默认 最新

  • dongzhong5756 2016-06-18 20:24
    关注

    Here's Nigel Tao's answer from https://groups.google.com/forum/#!topic/golang-nuts/zYlx6sR4F8Y:

    One reason is that arrays are value types. If a0 is an [N]int (an array) then doing

    a1 := a0
    a1[0] = 0
    

    will not affect a0[0] at all.

    In comparison, slices refer to an underlying array. Copying a slice value is O(1) instead of O(length). If s0 is an []int (a slice) then doing

    s1 := s0
    s1[0] = 0
    

    will affect what s0[0] is.

    http://play.golang.org/p/TVkntIsLo8

    Map keys need some notion of equality. For arrays, this is simply element-wise equality. For slices, there is more than one way to define equality: one is element-wise equality, another is referring to the same array backing store. Furthermore, does map insertion need to make an (expensive) copy of the entire backing array? Copying would probably be less surprising, but it is inconsistent with what assignment does.

    What should this code snippet print?

    m := make(map[[]int]bool)
    s0 := []int{6, 7, 8}
    s1 := []int{6, 7, 8}
    s2 := s0
    m[s0] = true
    s2[0] = 9
    println(m[s0])
    println(m[s1])
    println(m[s2])
    

    Different programmers can have different expectations. To avoid confusion, we have simply decided not to allow slices as map keys for now.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?