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")
}
回答
的<-运算符用于等待的信道的响应。在此代码中使用它来等待time.AfterX 时间后将提供的通道。
您可以在@Marc 提到的 Go 之旅中了解更多有关频道的信息。请注意,如果您不处理多通道结果(使用 as ),则<-time.After(time.Second * 2)可以将其替换为同步time.Sleep(time.Second * 2)语句select。
的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("operation timed out")
case result := <-resultchan
return result, nil
}
}
同样,我们强烈建议您参观 Go 以了解 Go 的基础知识:)