dsgfdgh14569 2018-10-04 21:23
浏览 38
已采纳

在函数中更改全局切片

I've never worked with C/C++, so I'm a bit stuck with pointers in go. The problem is: I have a map[string][]InteractiveItems for each "room" and I wanna change slice of it in a function. Here it is:

func (r *room) getItem(arg string) InteractiveItem {
for i, val := range r.interactiveItems {
    for _, item := range val {
        if item.getName() == arg {
            var idxToDelete int
            for idx := range val {
                if val[idx].getName() == arg {
                    idxToDelete = idx
                    break
                }
                if len(val) == 0 {
                    delete(r.interactiveItems, i)
                }
            }
            val = append(val[:idxToDelete], val[idxToDelete+1:]...)
            return item
        }
    }
}
return nil

Obviously, val is changing inside the function, but room's map is not. How should I deal with pointers to delete the element of a slice?

  • 写回答

1条回答 默认 最新

  • douqiao1997 2018-10-04 22:26
    关注

    This is because everything in Go is passed by value.

    What this means for your case is that when you are iterating over the map, on each iteration the val variable is assigned a copy of the corresponding slice value. So re-slicing the val value inside the loop has no effect on the original slice inside the map, since one is a copy of, not a reference to, the other.

    To change the slice that's inside the map you can re-assign the result of the append operation to the corresponding map key.

    r.interactiveItems[i] = append(val[:idxToDelete], val[idxToDelete+1:]...)
    

    Keep in mind that when a slice is copied it does not copy the data that the slice points to, it copies only the slice's "descriptor".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3