-2

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.

Grant Curell
  • 1,321
  • 2
  • 16
  • 32
  • 2
    The `timestamp` variable declared inside the if statement is not used. Fix by changing the [short variable declaration](https://go.dev/ref/spec#Short_variable_declarations) inside the if statement to [assignment](https://go.dev/ref/spec#Assignments): `timestamp, err = time.Parse(time.RFC3339, value.Timestamp)` –  Mar 01 '22 at 03:09
  • Ahhhhh it has to be in the same block to be allowed to do a redeclaration. That's what I missed – Grant Curell Mar 01 '22 at 03:36

1 Answers1

2

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)
colm.anseo
  • 19,337
  • 4
  • 43
  • 52
  • I wasn't able to suggest an edit because the queue was full, but as a novice go programmer I didn't understand that you *can* use a short variable declaration to redeclare a variable but it must be the *same block*. It's that last part that confused me – Grant Curell Mar 01 '22 at 03:35