doucheng1944 2017-11-26 18:17
浏览 97
已采纳

如何在Go中获取指向地图中的值的指针

I would like to get a pointer to a map value (which contains structs), so that I can modify a field in the struct, without having to re-assign it.

type Foo struct {
    Bar int64
}

func SomeFunction(arg * Foo) {
    ...
}

What I currently have to do:

if val, ok := myMap[idx]; ok {
  // val is of type `Foo`
  SomeFunction(&val)
  myMap[idx] = val
}

What I'd like to do:

if val, ok := getPointer(myMap, idx); ok {
  // val is of type `* Foo`
  SomeFunction(val)
}

Is there a way to do this Go, or do I need to rely on the compiler being smart enough to perform copy elision here?

  • 写回答

1条回答 默认 最新

  • duai3681 2017-11-26 21:46
    关注

    For this operation you may use map if pointers. Like:

    var myMap = map[int]*Foo
    
    if _, val := range myMap {
      // val is of type `* Foo`
      SomeFunction(val)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 fluent设置了自动保存后,会有几个时间点不保存
  • ¥20 激光照射到四象线探测器,通过液晶屏显示X、Y值
  • ¥15 这怎么做,怎么在我的思路下改下我这写的不对
  • ¥50 数据库开发问题求解答
  • ¥15 安装anaconda时报错
  • ¥20 如何用Python处理单元格内连续出现的重复词语?
  • ¥15 小程序有个导出到插件方式,我是在分包下引入的插件,这个export的路径对吗,我看官方文档上写的是相对路径
  • ¥20 希望有人能帮我完成这个设计( *ˊᵕˋ)
  • ¥100 将Intptr传入SetHdevmode()将Intptr传入后转换为DEVMODE的值与外部代码不一致
  • ¥50 基于ERA5数据计算VPD