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
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题