I have the following range over a slice of a specific struct:
var t1, t2 *time.Time
for _, d := range entries {
if d.EntryType == print {
t1 = &d.LogTime
}
if d.EntryType == saw {
t2 = &d.LogTime
}
}
In my example I have two objects in my struct and I know that they are different. But when I Println both Time pointers with String or when I make some calculations, I can see that both have the same value of the second one.
When I change the assignment to
tmp := d.LogTime
t1 = &tmp
i can make my calculations, because both pointers are pointing to different objects.
The application is taking the address of the variable d
, not the address of a slice element. The variable d
is scoped outside the loop and has the same address on each iteration of the loop.
The code
tmp := d.LogTime
t1 = &tmp
works because tmp
is scoped inside the loop.
Perhaps you intended to take the address of the slice element. If so, use this code:
for i:= range entries {
if d.EntryType == print {
t1 = &entries[i].LogTime
}
if d.EntryType == saw {
t2 = &entries[i].LogTime
}
}
There may be a reason to use *time.Time
values here, but typically applications work with time.Time
. This code may do what you need:
var t1, t2 time.Time
for _, d := range entries {
if d.EntryType == print {
t1 = d.LogTime
}
if d.EntryType == saw {
t2 = d.LogTime
}
}