【发布时间】:2015-02-17 15:25:43
【问题描述】:
我对初始化包含映射的结构的最佳方式感到困惑。运行这段代码会产生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)
}
一个想法是创建一个构造函数,如this answer。
另一个想法是使用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)
}
还有其他选择吗?只是想看看是否有一种普遍接受的方法来做到这一点。
【问题讨论】:
-
构造函数是普遍接受的方式(除了假设程序员可以独立完成)
标签: dictionary struct go