I would like to understand the meaning of this code:
<-
in the following snippet:
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)
}
While I understand what this code does (it prints doing something from polling every 2 seconds) I don't understand why <-
is being used outside of its normal context of sending to/receiving from channels.
Put in other words, I don't see a channel here.
time.After returns a channel:
func After(d Duration) <-chan Time
The <-time.After(...)
just waits until there is an element to read from the channel, which happens after the amount of time specified has elapsed. The channel value is the time after the duration.
This function is a package function, which should not be confused with the method on Time
: func (t Time) After(u Time) bool
which just returns whether t
is after u
. This method would be called with: if sometimevariable.After(...) {