字典 – golang – 如何初始化一个结构中的地图字段?
发布时间:2020-12-16 19:20:01 所属栏目:大数据 来源:网络整理
导读:我对初始化包含地图的结构体的最佳方式感到困惑。运行此代码会产生panic:运行时错误:分配给nil map中的条目: package maintype Vertex struct { label string} type Graph struct { connections map[Vertex][]Vertex} func main() { v1 := Vertex{"v1"} v
我对初始化包含地图的结构体的最佳方式感到困惑。运行此代码会产生panic:运行时错误:分配给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],v1) } 还有其他选择吗?只是想看看是否有一个普遍接受的方法来做到这一点。
我可能会使用一个构造函数来做到这一点:
func NewGraph() *Graph { var g Graph g.connections = make(map[Vertex][]Vertex) return &g } 我在标准的 type Alpha struct { Pix []uint8 Stride int Rect Rectangle } func NewAlpha(r Rectangle) *Alpha { w,h := r.Dx(),r.Dy() pix := make([]uint8,1*w*h) return &Alpha{pix,1 * w,r} } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |