如何在循环中使用指针更改切片元素

huangapple go评论80阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年6月20日 21:54:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/68056532.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定