3

How to avoid "unused variable in a for loop" error with code like

ticker := time.NewTicker(time.Millisecond * 500)
go func() {
    for t := range ticker.C {
        fmt.Println("Tick at", t)
    }
}()

if I actually don't use the t variable?

ain
  • 22,394
  • 3
  • 54
  • 74
Bruce
  • 181
  • 4
  • 11

2 Answers2

19

You don't need to assign anything, just use for range, like this (on play)

package main

import (
    "fmt"
    "time"
)

func main() {
    ticker := time.NewTicker(time.Millisecond * 500)
    go func() {
        for range ticker.C {
            fmt.Println("Tick")
        }
    }()
    time.Sleep(time.Second * 2)

}
David Budworth
  • 11,248
  • 1
  • 36
  • 45
12

Use a predefined _ variable. It is named "blank identifier" and used as a write-only value when you don't need the actual value of a variable. It's similar to writing a value to /dev/null in Unix.

for _ = range []int{1,2} {
    fmt.Println("One more iteration")
}

The blank identifier can be assigned or declared with any value of any type, with the value discarded harmlessly. It's a bit like writing to the Unix /dev/null file: it represents a write-only value to be used as a place-holder where a variable is needed but the actual value is irrelevant.

Update

From Golang docs:

Up until Go 1.3, for-range loop had two forms

for i, v := range x {
    ...
}

and

for i := range x {
    ...
}

If one was not interested in the loop values, only the iteration itself, it was still necessary to mention a variable (probably the blank identifier, as in for _ = range x), because the form

for range x {
   ...
}

was not syntactically permitted.

This situation seemed awkward, so as of Go 1.4 the variable-free form is now legal. The pattern arises rarely but the code can be cleaner when it does.

I159
  • 29,741
  • 31
  • 97
  • 132