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?
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?
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)
}
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.
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.