专栏名称: SegmentFault思否
SegmentFault (www.sf.gg)开发者社区,是中国年轻开发者喜爱的极客社区,我们为开发者提供最纯粹的技术交流和分享平台。
目录
相关文章推荐
三峡小微  ·  大国重器前的宣讲:单单的三峡情 ·  2 天前  
三峡小微  ·  “线性菲涅尔”光热储能电站的追光者 ·  4 天前  
51好读  ›  专栏  ›  SegmentFault思否

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

SegmentFault思否  · 公众号  ·  · 2024-04-26 11:59

正文

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

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

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

思路

  1. 1. 首先这个问题的思路在于能否作为 key 的条件是什么?

  2. 2. key 在 map 中的作用是标记一个 kv,我们需要用 key 去查找对应的 value

  3. 3. 那么我怎么知道,一个输入的 key 是否在这个 map 中呢?答案是比较

  4. 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,如下:

package main

import (
    "fmt"
)

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






请到「今天看啥」查看全文