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?