Рассмотрим следующую проблему.
У меня есть две структуры: Graph и 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
}
и эталонный приемник для Vertex
func (v *Vertex) Edge(t string, w decimal.Decimal) {
v.edges[t] = w
}
Я бы хотел в разное время обновлять значения карты Vertex.edges внутри структуры Graph.
Я изначально пробовал этот код, пришедший из 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)
}
Я получаю
# 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]
Поэтому я попытался изменить g.vertexes[person].Edge(friend, strength)
на:
pToVertex := &g.vertexes[person]
pToVertex.Edge(friend, nicestrength)
А теперь получите
./main.go:26:16: cannot take the address of g.vertexes[person]
Какое решение для этого?
ДА, этот вопрос был задан, но, насколько я понимаю, были только ответы, которые объясняют, почему это так. Теперь я понимаю почему, как мне решить мою проблему?