golang - 如何在结构中初始化地图字段? [英] golang - how to initialize a map field within a struct?

查看:18
本文介绍了golang - 如何在结构中初始化地图字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对初始化包含地图的结构的最佳方法感到困惑.运行此代码会产生 panic: runtime error: assignment to entry in nil map:

I'm confused about the best way to initialize a struct that contains a map. Running this code produces 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)
}

一个想法是创建一个构造函数,如这个答案.

One idea is to create a constructor, as in this answer.

另一个想法是使用一个 add_connection 方法,如果地图为空,它可以初始化地图:

Another idea is to use an add_connection method that can initialize the map if it's empty:

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)
}

还有其他选择吗?只是想看看是否有一种普遍接受的方法来做到这一点.

Are there other options? Just wanted to see if there is a commonly-accepted way to do this.

推荐答案

我可能会使用构造函数来做到这一点:

I would probably use a constructor to do this:

func NewGraph() *Graph {
    var g Graph
    g.connections = make(map[Vertex][]Vertex)
    return &g
}

我在标准中找到了这个例子image/jpeg 包(虽然没有地图,但有切片):

I've found this example in the standard image/jpeg package (not with a map though, but with a slice):

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}
}

这篇关于golang - 如何在结构中初始化地图字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆