What is the back arrow "<-" in Golang?

huangapple go评论77阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;time&quot;
)

func main() {
	a := 1
	fmt.Println(&quot;Starting&quot;)
	&lt;-time.After(time.Second * 2)
	fmt.Println(&quot;Printed after 2 seconds&quot;)
}

答案1

得分: 14

&lt;- 运算符用于等待通道的响应。在这段代码中,它用于等待由 time.After 提供的通道,在经过 X 时间后将被填充。

你可以在 Go 之旅 中了解更多关于通道的知识,这是 @Marc 提到的。请注意,如果你不处理多个通道结果(使用 select),&lt;-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 &lt;-time.After(time.Second * 2):
        return nil, fmt.Errorf("操作超时")
    case result := &lt;-resultchan:
        return result, nil
    }
}

再次强烈建议你参加 Go 之旅,以了解 Go 的基础知识 What is the back arrow "<-" in Golang?

英文:

The &lt;- 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 &lt;-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 &lt;-time.After(time.Second * 2):
        return nil, fmt.Errorf(&quot;operation timed out&quot;)
    case result := &lt;-resultchan
        return result, nil
    }
}

Again, we highly recommend you to take the tour of Go to get to know Go's basics What is the back arrow "<-" in Golang?

huangapple
  • 本文由 发表于 2021年7月19日 15:51:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/68436941.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定