前言

最近好忙,也好久没水 Golang 的文章了,最近来水一些。说回今天的问题,这个问题非常简单,也能被快速验证。

Golang 中 能否将 slice 作为 map 的 key?

如果你现实中使用过,那么这个问题对于你来说其实意义不大,因为不行就是不行,可以就是可以。

如果你完全没这样使用过 map,那么这个问题对于你来说可能就有意义了。

思路

  1. 首先这个问题的思路在于能否作为 key 的条件是什么?
  2. key 在 map 中的作用是标记一个 kv,我们需要用 key 去查找对应的 value
  3. 那么我怎么知道,一个输入的 key 是否在这个 map 中呢?答案是比较
  4. 所以只要这个 key 能比较,说白了就是能使用 “==” 进行比较,大概率就没有问题

所以其实,这个问题的本质是:“slice 能否进行比较?”

答案

答案显然是不能的,因为 slice 是不能使用 “==” 进行比较的,所以是不能做为 map 的 key 的。
而官方文档中也说明了 https://go.dev/blog/maps

As mentioned earlier, map keys may be of any type that is comparable. The language spec defines this precisely, but in short, comparable types are boolean, numeric, string, pointer, channel, and interface types, and structs or arrays that contain only those types. Notably absent from the list are slices, maps, and functions; these types cannot be compared using ==, and may not be used as map keys.

所以如果真的需要以 slice 类似的数据来作为 key,你需要使用 array 而不是 slice,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

import (
"fmt"
)

func main() {
var a, b [1]int
a = [1]int{1}
b = [1]int{2}
m := make(map[[1]int]bool)
m[a] = true
m[b] = true

for i := 0; i < 3; i++ {
fmt.Println(m[[1]int{i}])
}
}

那么只要数组中的每个对应下标元素相等,则 key 相等