首页 > 解决方案 > 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")
}

标签: go

解决方案


<-运算符用于等待通道的响应。在此代码中使用它来等待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 的基础知识 :)


推荐阅读