我想理解这段代码的含义:
<-
在下面的片段中:
package main
import (
"fmt"
"net/http"
"time"
)
func doSomething(s string) {
fmt.Println("doing something", s)
}
func startPolling() {
for {
// Here:
<-time.After(2 * time.Second)
go doSomething("from polling")
}
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello")
}
func main() {
go startPolling()
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
虽然我理解这段代码的作用(它每 2 秒打印一次 doing something from polling),但我不明白为什么 <-
在发送到 channel /从 channel 接收的正常上下文之外使用。
换句话说,我在这里看不到 channel 。
最佳答案
time.After返回一个 channel :
func After(d Duration) <-chan Time
<-time.After(...)
只是等到有一个元素从 channel 中读取,这发生在指定的时间量过去之后。 channel 值是持续时间之后的时间。
这个函数是一个封装函数,不要和Time
上的方法混淆:
func (t Time) After(u Time) bool
它只返回是否 t
在u
之后.此方法将被调用:if sometimevariable.After(...) {
关于go - channel 接收运算符与不是 channel 的东西一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48705361/