【问题标题】:golang - how to initialize a map field within a struct?golang - 如何初始化结构中的映射字段?
【发布时间】: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


【解决方案1】:

复合文字在构造函数中工作得很好。使用最初的问题设计一个示例(并在地图中天真地存储顶点的副本):

func NewGraph(v1 Vertex, v2 Vertex) *Graph {
    return &Graph{ map[Vertex][]Vertex{ v1: []Vertex{v2}, v2: []Vertex{v1} }}
}

func main() {
  v1 := Vertex{"v1"}
  v2 := Vertex{"v2"}

  g := NewGraph(v1, v2)
  fmt.Println(g)
}

https://play.golang.org/p/Lf4Gomp4tJ

【讨论】:

    【解决方案2】:

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

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

    我在标准的image/jpeg 包中找到了这个示例(虽然不是带有地图,而是带有切片):

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

    【讨论】:

    • 太好了,感谢您在标准库中找到示例,这绝对激发了信心
    【解决方案3】:

    假设您正确初始化数据结构,代码(尤其是完全由您控制的代码)是很常见的。在这种情况下通常使用结构字面量

    g := &Graph{
        connections: make(map[Vertex][]Vertex),
    }
    

    【讨论】:

    • 但是如何用某个特定值初始化连接值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    相关资源
    最近更新 更多