Home > Software design >  Struct's field's value resets on each iteration
Struct's field's value resets on each iteration

Time:09-17

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?

CodePudding user response:

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
}
  • Related