Go believes variables inside conditional statements are unused?

479 Views Asked by At

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.

1

There are 1 best solutions below

1
colm.anseo On

The nested (inner) timestamp declaration 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's timestamp (and err) values:

timestamp, err = time.Parse(time.RFC3339, value.Timestamp)