英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论