如何在不使用循环变量的情况下构建一个适用于循环的计时器

huangapple go评论74阅读模式
英文:

How to build a tick for loop without using the loop variable

问题

我有一个循环,它在一个时间间隔内持续运行,但我只想将其作为一个每10分钟运行一次的函数使用。如何声明这个循环而不必在循环内部使用'x'?

interval := time.Tick(10 * time.Minute)

for x := range interval {
...不使用x的代码
}

我尝试重新构建这个循环,但没有任何结果可以在不特别使用'x'的情况下运行它。我知道我可以在循环内部简单地使用'x',但我更愿意学习如何正确实现这个循环,而不是使用一个技巧。

英文:

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.

答案1

得分: 6

要翻译的内容如下:

要么

for {
        <-time.After(someTime)
        // ...
}

要么

interval := time.Tick(someTime)

for ; ; <-interval { // First interval == 0
        // ...
}

要么

interval := time.Tick(someTime)

for {
        <-interval
        // ...
}
英文:

Either

for {
        <-time.After(someTime)
        // ...
}

or

interval := time.Tick(someTime)

for ; ; <-interval { // First interval == 0
        // ...
}

or

interval := time.Tick(someTime)

for {
        <-interval
        // ...
}

答案2

得分: 5

你可以使用_来表示你将忽略的变量:

interval := time.Tick(10 * time.Minute)

for _ = range 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.

答案3

得分: 0

从go1.4(2014年第四季度)开始,您可以这样声明for循环而不必在循环内部使用'x':

for range interval {
  ...
}

参见go tip 1.4 doc

从Go 1.4开始,无变量形式现在是合法的
这种模式很少出现,但当出现时,代码可以更清晰。

更新:此更改与现有的Go程序严格兼容,但分析Go解析树的工具可能需要修改以接受此新形式,因为RangeStmtKey字段现在可以是nil

英文:

> 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 of RangeStmt may now be nil.

huangapple
  • 本文由 发表于 2013年5月3日 22:31:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/16361346.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定