Can you imagine waiting forever for something to perform an action? Neither can I! So, in this section you will learn how to implement timeouts in Go with the help of the select statement.
The program with the sample code will be named timeOuts.go and will be presented in four parts; the first part is the following:
package main import ( "fmt" "time" )
The second part of timeOuts.go is the following:
func main() { c1 := make(chan string) go func() { time.Sleep(time.Second * 3) c1 <- "c1 OK" }()
The time.Sleep() statement in the goroutine is used for simulating the time it will take for the goroutine to do its real job.
The third part of timeOuts.go has the following code:
select { case res := <-c1: fmt.Println(res) case <-time.After(time.Second * 1): ...