Goroutines and Channels

Table of Contents

Goroutines tutorial

Basics of chan (Channels) tutorial

ch := make(chan int)    // unbuffered
ch := make(chan int, 0) // unbuffered
ch := make(chan int, 3) // buffered with capacity 3

ch <- x  // a send statement
<-ch     // a receive statement; result is discarded
x = <-ch // a receive expression in an assignment statement

// `close' sets a flag indicating that no more values will ever be sent on this channel;
// subsequent attempts to send will panic.
// Receive operations on a closed channel yield the values that have been sent until no more values are left;
close(ch)
ch := make(chan int)
for {
    x, ok := <-ch
    if !ok {
        break // channel was closed and drained
    }
    // Do something with x
}

// Instead of doing it clumsy, just use range
for x := range ch {
    // Do something with x
}
func sendOnly(ch chan<- int)
func recvOlny(ch <-chan int)
Two of these goroutines won't finish.
As like other functions, the iterator variable changes over iteration. So in case running gorotine within a loop, pass it as a same-named argument

Avoid a data race howto

Goroutines and Threads discussion