using select to implement timeout

tags: learning go programming

content

  • because select basically means waiting for something (see here), we can use select to implement a timeout logic
func main() {
	ch := make(chan int, 1)
	go func() { do something }()
	select {
	case result := <- ch:
		fmt.Println("result from operation", result)
	case <-time.After(2 * time.Second):
		fmt.Println("operation timeout after 2s")
	}
}

up

down