结构体字段的值在每次迭代时重置

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

Struct's field's value resets on each iteration

问题

你的问题是每次迭代时,Status字段的值都被重置了。这是因为在循环中,你使用的是range关键字返回的副本而不是原始的Device结构体。因此,对副本的修改不会影响原始的devices列表。

要解决这个问题,你可以通过使用索引来访问每个设备,并直接修改原始的devices列表中的元素。这样,修改后的值将保留在下一次迭代中。

以下是修改后的代码示例:

func main() {
	for range time.Tick(2 * time.Second) {
		for i := range devices {
			fmt.Printf("%s: %v\n", devices[i].Name, devices[i].Status)
			devices[i].Status = true
			fmt.Printf("%s: %v\n--------\n", devices[i].Name, devices[i].Status)
		}
	}
}

这样修改后,你应该能够得到预期的输出结果。

希望能帮到你!如果你还有其他问题,请随时问。

英文:

I have a Device struct with Name, IP and Status fields; I have a list of devices; I want to iterate over that list every 2 seconds (or any other amount of time, for that matters) and change the Status field:

type Device struct {
	Name   string
	IP     string
	Status bool
}

// One device is enough to explain the problem
var devices = []Device{
	Device{Name: "phone", IP: "192.168.1.58", Status: false},
}

func main() {
	for range time.Tick(2 * time.Second) {
		for _, j := range devices {
			fmt.Printf("%s: %v\n", j.Name, j.Status)
			j.Status = true
			fmt.Printf("%s: %v\n--------\n", j.Name, j.Status)
		}
	}
}

I would expect the output to be

phone: false
phone: true
------
phone: true
phone: true
------
phone: true
phone: true
------
...

but instead I get

phone: false
phone: true
--------
phone: false
phone: true
--------
...

Basically, the Status value is reset on each iteration.

If I move my device outside a list, it works as expected, like this:

var j = Device{Name: "phone", IP: "192.168.1.58", Status: false}

for range time.Tick(2 * time.Second) {
    fmt.Printf("%s: %v\n", j.Name, j.Status)
	j.Status = true
	fmt.Printf("%s: %v\n--------\n", j.Name, j.Status)
}

What am I doing wrong?

答案1

得分: 1

你可以按照 @Marc 的建议将切片类型更改为指针类型;或者你可以直接通过索引更新切片:

for i := range devices {
    devices[i].Status = true
}
英文:

You can change your slice type to a pointer as @Marc suggested; or you can just update the slice directly via its index:

for i := range devices {
    devices[i].Status = true
}

huangapple
  • 本文由 发表于 2021年9月16日 05:01:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/69199742.html
匿名

发表评论

匿名网友

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

确定