package channel import ( "fmt" "sync" "time" ) func ExampleUnbufferedSend() { c1 := make(chan string) wg := &sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() select { case c1 <- "got message": return case <-time.After(20 * time.Millisecond): return } }() wg.Wait() // explicitly defer until goroutine is done select { case msg := <-c1: fmt.Println(msg) default: fmt.Println("no message") } // Output: no message } func ExampleBufferedSend() { c1 := make(chan string, 1) wg := &sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() select { case c1 <- "got message": return case <-time.After(20 * time.Millisecond): return } }() wg.Wait() // explicitly defer until goroutine is done select { case msg := <-c1: fmt.Println(msg) default: fmt.Println("no message") } // Output: got message } func ExampleNilChannelSend() { var c1 chan string wg := &sync.WaitGroup{} wg.Add(1) result := make(chan string, 1) go func() { defer wg.Done() select { case c1 <- "got message": return case <-time.After(20 * time.Millisecond): result <- "nil channel send blocks" return } }() wg.Wait() select { case msg := <-c1: fmt.Println(msg) case msg := <-result: fmt.Println(msg) } // Output: nil channel send blocks } func ExampleClosedChannelSend() { c1 := make(chan string, 1) close(c1) // using a channel so we know when its done result := make(chan string) go func() { defer func() { if r := recover(); r != nil { // handling the panic of the send on closed channel that will happen below result <- r.(error).Error() return } result <- "timed out" }() select { case c1 <- "got message": // closed channels panic when you send on them return case <-time.After(20 * time.Millisecond): return } }() fmt.Println(<-result) // Output: send on closed channel } func ExampleCloseNilChannel() { defer func() { if r := recover(); r != nil { // handling the panic of the close of nil channel fmt.Println(r) return } fmt.Println("timed out") }() var c1 chan string close(c1) // close of nil channel panics // Output: close of nil channel } func ExampleWaitArbitraryNumberOfChannels() { }