I have a for loop that continually runs over an interval, however I am only using it as a function that I want running every 10 Minutes. How can I declare this for-loop without having to use 'x' somewhere inside of the loop
interval := time.Tick(10 * time.Minute)
for x := range interval {
...code that does not use x
}
I have tried restructuring the for loop but nothing results in it running without specifically using 'x', I know I could just simply do something with 'x' inside of the loop, but I would rather learn how to properly implement this for loop then make a hack.
Either
for {
<-time.After(someTime)
// ...
}
or
interval := time.Tick(someTime)
for ; ; <-interval { // First interval == 0
// ...
}
or
interval := time.Tick(someTime)
for {
<-interval
// ...
}
You can use _
to denote variables that you will ignore:
interval := time.Tick(10 * time.Minute)
for _ = range interval {
...
}
The spec says:
The blank identifier, represented by the underscore character _, may be used in a declaration like any other identifier but the declaration does not introduce a new binding.
How can I declare this for-loop without having to use 'x' somewhere inside of the loop
Starting go1.4 (Q4 2014), you will be able to do:
for range interval {
...
}
See go tip 1.4 doc:
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.Updating: The change is strictly backwards compatible to existing Go programs, but tools that analyze Go parse trees may need to be modified to accept this new form as the
Key
field ofRangeStmt
may now benil
.