我对包含映射的结构体初始化的最佳方法感到困惑。运行这段代码会产生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)
}
一个想法是创建一个构造函数,例如这个答案中所示。
另一个想法是使用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)
}
还有其他选项吗?只是想知道是否有一种通常被接受的方法来做到这一点。