duanmuybrtg1231 2018-05-10 00:08
浏览 12
已采纳

如何访问Structs内部的地图? 无法使用g.vertexes [base]的地址

Consider the following issue.

I have two structs, Graph and Vertex

package main

import (
  "github.com/shopspring/decimal"
)

type Graph struct {
  vertexes map[string]Vertex
}

type Vertex struct {
  key string
  edges map[string]decimal.Decimal
}

and a reference receiver for Vertex

func (v *Vertex) Edge(t string, w decimal.Decimal) {
  v.edges[t] = w
}

I would like to update at various times the values of the Vertex.edges map inside the Graph struct.

I initially tried this code, coming from Python:

func UpdateGraph(person, friend, strength string, g *Graph) decimal.Decimal {
  nicestrength, _ := decimal.NewFromString(strength)
  g.vertexes[person].Edge(friend, nicestrength)
  return nicestrength
}

func main() {
  people := []string{"dave", "tim", "jack"}
  g := Graph{make(map[string]Vertex)}
  for _, p := range people {
    g.vertexes[p] = Vertex{p, make(map[string]decimal.Decimal)}
  }
  UpdateGraph("dave", "jack", "0.3434555444433444", &g)
}

I get

# command-line-arguments
./main.go:28:19: cannot call pointer method on g.vertexes[person]
./main.go:28:19: cannot take the address of g.vertexes[person]

So I tried amending g.vertexes[person].Edge(friend, strength) to:

pToVertex := &g.vertexes[person]
pToVertex.Edge(friend, nicestrength)

And now receive

./main.go:26:16: cannot take the address of g.vertexes[person]

What's the solution to this?

YES, this question has been asked but as far as I can see there have only been answers which explain why it is the case. Now I understand why, how do I solve my problem?

  • 写回答

1条回答 默认 最新

  • douzhu5900 2018-05-10 12:16
    关注

    Two options:

    1. Change the Edge method so that it doesn't use a pointer receiver:

      func (v Vertex) Edge(t string, w decimal.Decimal) {
        v.edges[t] = w
      }
      

      Because edges is a map, and maps are pointers behind the scenes, updates will be propagated despite the non-pointer receiver

    2. Store Vertex pointers:

      type Graph struct {
        vertexes map[string]*Vertex
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?