I have a situation where if something fails to assign a variable I instead assign it within a conditional statement however Go seems to think this variable is unused.
for index, value := range group.Values {
timestamp, err := time.Parse(time.RFC3339, value.Timestamp)
if err != nil {
strings.ReplaceAll(value.Timestamp, "+0000", "")
timestamp, err := time.Parse(time.RFC3339, value.Timestamp)
if err != nil {
log.Printf("Error parsing timestamp for point %s: (%s) %v", value.Context+"_"+value.ID, value.Timestamp, err)
continue
}
}
event := new(SplunkEvent)
event.Time = timestamp.Unix()
Go believes the variable timestamp inside the conditional statement is unused. Why is that? I have clearly used it directly after the condition.
The nested (inner)
timestampdeclaration shadows the outer one - so the outer one is never set. So since the inner value is never used, the compilation error is valid.To fix, replace
:=declared assignment operator with=to (re)use the outer scope'stimestamp(anderr) values: