英文:
What is the back arrow "<-" in Golang?
问题
我在一小段代码中使用它来使time.After()
函数生效,如果没有它,程序将直接执行下一行代码,而不会等待计时器完成。
以下是示例代码:
package main
import (
"fmt"
"time"
)
func main() {
a := 1
fmt.Println("Starting")
<-time.After(time.Second * 2)
fmt.Println("Printed after 2 seconds")
}
英文:
I used it in a small piece of code to make time.After()
work, without it the program simply goes on to the next line without waiting for the timer to finish.
This is the example:
package main
import (
"fmt"
"time"
)
func main() {
a := 1
fmt.Println("Starting")
<-time.After(time.Second * 2)
fmt.Println("Printed after 2 seconds")
}
答案1
得分: 14
<-
运算符用于等待通道的响应。在这段代码中,它用于等待由 time.After
提供的通道,在经过 X 时间后将被填充。
你可以在 Go 之旅 中了解更多关于通道的知识,这是 @Marc 提到的。请注意,如果你不处理多个通道结果(使用 select
),<-time.After(time.Second * 2)
可以被同步的 time.Sleep(time.Second * 2)
语句替代。
time.After
通常用于在涉及一个或多个通道的异步操作中设置结果超时,类似于以下示例:
func doLongCalculations() (int, error) {
resultchan := make(chan int)
defer close(resultchan)
go calculateSomething(resultchan)
select {
case <-time.After(time.Second * 2):
return nil, fmt.Errorf("操作超时")
case result := <-resultchan:
return result, nil
}
}
再次强烈建议你参加 Go 之旅,以了解 Go 的基础知识
英文:
The <-
operator is used to wait for a response of a channel. It is used in this code to wait for a channel provided by the time.After
that will be fed after X amount of time.
You can know more about channels in the tour of Go that @Marc mentioned. And note that <-time.After(time.Second * 2)
can be replaced with the synchronous time.Sleep(time.Second * 2)
statement, if you're not dealing with multiple channel results (with as select
).
The time.After
is usually used when timing out a result from a asynchronous operation involving one or more channels, something like this:
func doLongCalculations() (int, error) {
resultchan := make(chan int)
defer close(resultchan)
go calculateSomething(resultchan)
select {
case <-time.After(time.Second * 2):
return nil, fmt.Errorf("operation timed out")
case result := <-resultchan
return result, nil
}
}
Again, we highly recommend you to take the tour of Go to get to know Go's basics
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论