4

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?

0

2 Answers 2

22

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)

}
Sign up to request clarification or add additional context in comments.

Comments

13

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.

2 Comments

Go 1.4 removed the need for this. for range <range> is perfectly valid syntax now.
If range returns two variables and you only need one of them, do for _, y in range <range>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.