go - 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.After
将在 X 时间后馈送的通道。
您可以在@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 的基础知识 :)
推荐阅读
- php - 使用 CloudWatch 在 AWS 上的 Symfony 应用程序中的 PHP 日志目标
- php - 无法将关联字符串转换为关联数组
- node.js - 如何使用 express(客户端和管理员)提供 2 个不同的文件夹
- php - 根据是否选中复选框,在提交时返回 0 或 1 - 联系表 7
- javascript - 如何禁用同一行的其他输入字段
- c# - 如何正确使用正则表达式在 C# 中完成 HTML 中的元素?
- python - Python:Popen 与批处理
- spring-mvc - @RequestMapping 注解返回错误的 URL
- icalendar - iCalendar:没有 BYDAY 或 BYMONTHDAY 的每月规则
- css - 单击引导下拉菜单的背景颜色