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

Viewed 2908

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 (
    "fmt"
    "time"
)

func main() {
    a := 1
    fmt.Println("Starting")
    <-time.After(time.Second * 2)
    fmt.Println("Printed after 2 seconds")
}
1 Answers

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

Again, we highly recommend you to take the tour of Go to get to know Go's basics :)

Related