difference between below two code snippets
tags: learning go programming diff-between
content
- snippet 1
time.Afteris outside of theforloop
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.Afteroutside theforloop is easy to understand:- only 1 timeout, after 5 seconds,
selectstatement will definitely receive the timeout - and
returnstatement will definitely be reached - meaning, after 5 seconds, the whole thing times out
- only 1 timeout, after 5 seconds,
- snippet 2
time.Afteris insideselect, which is insidefor
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.Afterinside theforloop means that it’s being created all the time- if
cis received inselect, code execution moves on, currentforloop iteration finishes, next iteration starts - if
time.Afteris received,returnis reached, the whole thing stops
- if
Note
difference is that:
- snippet 1: cancel the whole operation after 5 seconds
- snippet 2: cancel the whole operation if
cis received less frequently than 1 second