我对初始化包含地图的结构的最佳方法感到困惑.运行此代码会产生panic: runtime error: assignment to entry in nil map:
package main
type Vertex struct {
label string
}
type Graph struct {
connections map[Vertex][]Vertex
}
func main() {
v1 := Vertex{"v1"}
v2 := Vertex{"v2"}
g := new(Graph)
g.connections[v1] = append(g.coonections[v1], v2)
g.connections[v2] = append(g.connections[v2], v1)
}
Run Code Online (Sandbox Code Playgroud)
一个想法是创建一个构造函数,如在这个答案中.
另一个想法是使用一种add_connection方法,如果它是空的,可以初始化地图:
func (g *Graph) add_connection(v1, v2 Vertex) {
if g.connections == nil {
g.connections = make(map[Vertex][]Vertex)
}
g.connections[v1] = append(g.connections[v1], v2)
g.connections[v2] = append(g.connections[v2], v1)
}
Run Code Online (Sandbox Code Playgroud)
还有其他选择吗?只是想看看是否有一种普遍接受的方式来做到这一点.