英文:
GO language how to change value of object inside of pointer of map
问题
我可以帮你翻译。以下是要翻译的内容:
我该怎么做?
我有一个对象列表,我想列出所有对象并更改对象的名称。
我有这个列表,并且我正在使用 while 循环将其发送到另一个函数,在那里我更改了名称,但名称没有保存。
有什么办法可以解决这个问题吗?
https://play.golang.org/p/el3FtwC-3U
如果有任何可以让我学到更多的书籍,请告诉我。
谢谢你的帮助 =D
英文:
How can I do it?
I have the list of objects, I want list all and change the name of object.
I have the list and I'm doing a while end send to another function, there I change the name, but the name doesn't save.
Any idea how can I do it?
https://play.golang.org/p/el3FtwC-3U
And if there is any book that I can read to learn more, please.
Thank for helping me =D
答案1
得分: 0
我没有找到如何获取映射中值的指针,所以我认为你需要使用map[string]*Track
,然后在你的Working
函数中使用指向Track
结构体的指针。
参考链接:https://play.golang.org/p/2XJTcKn1md
如果你想要并行修改tracks,你可能需要像这样的代码:https://play.golang.org/p/1GhST34wId
请注意通道中缺少缓冲区和在for range tracks
中使用go Working
。
英文:
I didn't found how to get pointer to value in map so I think you have to use map[string]*Track
instead and then work with pointers to Track
structure in your Working
function.
See https://play.golang.org/p/2XJTcKn1md
If you are trying modify tracks in parallel you are may be looking for something like this https://play.golang.org/p/1GhST34wId
Note missing buffer in chanel and go Working
in for range tracks
.
答案2
得分: 0
在范围循环中:
for _, track := range tracks {
// 将 track 发送到通道以更改名称
Working(&track, &c)
}
track
变量实际上是映射中包含的值的副本,因为此处的赋值操作适用于 Track
值类型,在 Go 中,赋值时会复制值。
相反,你应该使用映射的键,并在循环内部分配值。
for key := range tracks {
t := tracks[key]
// 将 track 发送到通道以更改名称
Working(&t, &c)
tracks[key] = t
}
参考:https://play.golang.org/p/9naDP3SfNh
英文:
In the range loop:
for _, track := range tracks {
// send track to channel to change the name
Working(&track, &c)
}
the track
variable is actually a copy of the value contained in the map, because the assignement here works on the Track
value type, and in Go, values are copied when assigned.
What you should do instead is use the key of your map and assign the values from within the loop.
for key := range tracks {
t := tracks[key]
// send track to channel to change the name
Working(&t, &c)
tracks[key] = t
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论