go - 使用 [][]int slice 超出范围但适用于 map[int][]int

标签 go go-map

为什么这段代码有效

graph := make(map[int][]int, 0)

graph[0] = append(graph[0], 1)

但是如果你用 graph := make([][]int, 0) 替换第一行,我会得到 panic: runtime error: index out of range?这很奇怪。

最佳答案

让我们简化您的代码,使发生的事情更加明显(Playground link):

graph1 := make(map[int]int, 0)
graph2 := make([]int, 0)

x := graph1[0] // Success
y := graph2[0] // Panic

由此我们可以看出,差异是由于 map[int][]int 造成的——您的类型中的第二个数组实际上是不相关的。

现在要了解为什么会发生这种情况,我们需要了解 Go 如何处理映射和 slice 访问。来自 Go Maps in Action我们学习:

If the requested key doesn't exist, we get the value type's zero value.

在您的原始代码中, slice ([]int) 的零值为 nil,并且 append()nil 作为空 slice 的第一个参数。

但是当我们尝试访问空 slice 的第 0 元素时,我们会出现 panic ,因为 slice 是空的。

总而言之,append 和您的类型的第二个片段在您的问题中都是转移注意力的问题。尝试访问 slice 的第一维中不存在的元素时会发生 panic 。

关于go - 使用 [][]int slice 超出范围但适用于 map[int][]int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50427411/

相关文章:

go routines 在下载大文件时挂起

Golang 将变量声明为 NULL

select - 当涉及多个 channel 时,select 如何工作?

go - map[string]interface{} 和 interface{} 的区别

json - 将 colly 包输出文本添加到 golang 中的映射

go - 无法在 Go 中获取文件的内容类型

go - 类型为 "set"的 channel

dictionary - 如何检查 map 是否包含 Go 中的键?

dictionary - 如何检查 map 是否包含Go中的键?

go - 在 Go 中有没有办法将结构映射转换为结构 slice