英文:
How to change slice elements using pointers in a loop
问题
我正在尝试在循环中使用指针原地更新切片中的一组结构体,但它们没有被更新。
package main
import "fmt"
type X struct {
ID float32
}
func inc(x *X) {
x.ID += 10
}
func main() {
var a = []X{X{}, X{}}
for _, v := range a {
inc(&v)
}
fmt.Println(a)
}
我错过了什么?
英文:
I'm trying to update a bunch of structs in a slice in place using pointers in a loop but they're not being updated.
package main
import "fmt"
type X struct {
ID float32
}
func inc(x *X) {
x.ID += 10
}
func main() {
var a = []X{X{}, X{}}
for _, v := range a {
inc(&v)
}
fmt.Println(a)
}
What am I missing?
答案1
得分: 4
在for _, v := range a
中,v
包含元素的副本。
改用索引访问:
for i := range a {
inc(&a[i])
}
英文:
In for _, v := range a
, v
contains a copy of the element.
Use indexed access instead:
for i := range a {
inc(&a[i])
}
答案2
得分: 1
上面的答案是正确的,这里添加一个链接作为参考-https://tour.golang.org/moretypes/16
当遍历一个切片时,每次迭代会返回两个值。第一个是索引,第二个是该索引处元素的副本。
抱歉,我不能评论,因为我没有足够的声望。所以,将其作为答案添加。
英文:
Above answer is correct, adding this link here as reference - https://tour.golang.org/moretypes/16
> When ranging over a slice, two values are returned for each iteration.
> The first is the index, and the second is a copy of the element at
> that index.
Sorry, I can't comment as I don't have the required reputation. So, adding it as answer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论