考虑以下问题。
我有两个结构,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
}
我想在不同时间更新 Graph 结构内 Vertex.edges 映射的值。
我最初尝试了这段来自 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]
解决这个问题的方法是什么?
是的,有人问过这个问题,但据我所知,只有答案可以解释为什么会这样。现在我明白为什么了,我该如何解决我的问题?
最佳答案
两种选择:
更改
Edge
方法,使其不使用指针接收器:func (v Vertex) Edge(t string, w decimal.Decimal) { v.edges[t] = w }
因为
edges
是一个映射,而映射是幕后的指针,所以尽管接收者不是指针,更新也会被传播存储
顶点
指针:type Graph struct { vertexes map[string]*Vertex }
关于go - 如何访问 Structs 内部的 map ?不能获取 g.vertexes[base] 的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50263716/