英文:
How timed loop works?
问题
我正在学习Golang,并且刚刚了解到定时循环(timed loop)。但是我不明白它是如何工作的。
for _ = range time.Tick(time.Second * 3) {
fmt.Println("Ticking every 3 seconds")
}
这段代码会每隔3秒钟执行一次循环体内的代码,使用time.Tick
函数来生成一个每隔指定时间间隔发送一个时间值的通道。range
关键字用于迭代通道,每次迭代都会接收到一个时间值,但由于我们对该值不感兴趣,所以使用_
来忽略它。循环体内的代码会在每次接收到时间值时执行,从而实现每隔3秒钟执行一次的效果。
英文:
I am learning golang, and I just came to know about the timed loop. But I don't understand how is it working?
for _ = range time.Tick(time.Second * 3) {
fmt.Println("Ticking every 3 seconds")
}
答案1
得分: 6
Tick函数返回一个<-chan Time
类型的通道,在Go语言中,使用range
循环遍历通道与遍历数组或映射一样简单。当你遍历一个通道时,循环内的代码会在每次从通道接收到数据时执行,就像你的例子中每3秒接收一次数据一样。当通道关闭后,循环会终止。
你可以参考这个链接:https://tour.golang.org/concurrency/4
英文:
Tick returns a <-chan Time
channel, and in Go looping over channels with range
, just as you would loop over an array or a map, is a ok. When you loop over a channel the code inside the loop gets executed on every recieve
from that channel, which in your example would happen every 3 seconds. The loop terminates after that channel is closed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论