go - 如何访问 Structs 内部的 map ?不能获取 g.vertexes[base] 的地址

标签 go

考虑以下问题。

我有两个结构,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]

解决这个问题的方法是什么?

是的,有人问过这个问题,但据我所知,只有答案可以解释为什么会这样。现在我明白为什么了,我该如何解决我的问题?

最佳答案

两种选择:

  1. 更改 Edge 方法,使其不使用指针接收器:

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

    因为 edges 是一个映射,而映射是幕后的指针,所以尽管接收者不是指针,更新也会被传播

  2. 存储顶点指针:

    type Graph struct {
      vertexes map[string]*Vertex
    }
    

关于go - 如何访问 Structs 内部的 map ?不能获取 g.vertexes[base] 的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50263716/

相关文章:

types - 在 Go 中实现堆栈以存储结构的正确方法是什么?

go - 与一对多的无效关联

go - 如何在golang中将*multipart.FileHeader文件类型转换为*os.File

linux - 如何使用 golang 加密文件夹

linux - 在使用 inotifywait 时遇到问题,试图观察 golang 更改的目录

go - nohup 返回到 golang 中的程序

amazon-web-services - k8s 使用 OwnerRef 获取集群中的所有 pod 层次结构

http - 在包级别声明互斥变量是一种好习惯吗?

mysql - 如何在Golang中使用GORM在数据库之间切换?

go - 在多行中共享代码