我有一个带有名称,IP和状态字段的结构;我有一个设备列表;我想每2秒(或任何其他时间,就此而言)迭代该列表并更改“状态”字段:Devicetype Device struct { Name string IP string Status bool}// One device is enough to explain the problemvar 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) } }}我预计输出是phone: falsephone: true------phone: truephone: true------phone: truephone: true------...但相反,我得到了phone: falsephone: true--------phone: falsephone: true--------...基本上,状态值在每次迭代时都会重置。如果我将设备移到列表之外,它将按预期工作,如下所示: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)}我做错了什么?
1 回答
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
您可以按照建议将切片类型更改为指针@Marc;或者,您可以直接通过其索引更新切片:
for i := range devices { devices[i].Status = true}
- 1 回答
- 0 关注
- 76 浏览
添加回答
举报
0/150
提交
取消