Quick actions

cmd+k|ctrl+k

Navigation

Languages

Channels and select / Timeout reading from channel with select / Essential Go

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-03-26T09:42:00Z

Updated

2019-03-26T09:42:00Z

package main

import (
	"fmt"
	"time"
)

func main() {
	chResult := make(chan int, 1)

	go func() {
		time.Sleep(1 * time.Second)
		chResult <- 5
		fmt.Printf("Worker finished")
	}()

	select {
	case res := <-chResult:
		fmt.Printf("Got %d from worker\n", res)
	case <-time.After(100 * time.Millisecond):
		fmt.Printf("Timed out before worker finished\n")
	}
}
INFO