difference between below two code snippets

tags: learning go programming diff-between

content

  • snippet 1
    • time.After is outside of the for loop
func main() {
    c := boring("Joe")
    timeout := time.After(5 * time.Second)
    for {
        select {
        case s := <-c:
            fmt.Println(s)
        case <-timeout:
            fmt.Println("You talk too much.")
            return
        }
    }
}
  • time.After outside the for loop is easy to understand:
    • only 1 timeout, after 5 seconds, select statement will definitely receive the timeout
    • and return statement will definitely be reached
    • meaning, after 5 seconds, the whole thing times out
  • snippet 2
    • time.After is inside select, which is inside for
func main() {
    c := boring("Joe")
    for {
        select {
        case s := <-c:
            fmt.Println(s)
        case <-time.After(1 * time.Second):
            fmt.Println("You're too slow.")
            return
        }
    }
}
  • time.After inside the for loop means that it’s being created all the time
    • if c is received in select, code execution moves on, current for loop iteration finishes, next iteration starts
    • if time.After is received, return is reached, the whole thing stops

Note

difference is that:

  • snippet 1: cancel the whole operation after 5 seconds
  • snippet 2: cancel the whole operation if c is received less frequently than 1 second

up

down

reference