
Introducing Go: Build Reliable, Scalable Programs

A goroutine is a function that is capable of running concurrently with other functions. To create a goroutine, we use the keyword go followed by a function invocation:
Caleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
Select Go has a special statement called select that works like a switch but for channels: func main() { c1 := make(chan string) c2 := make(chan string) go func() { for { c1 <- "from 1" time.Sleep(time.Second * 2) } }() go func() { for { c2 <- "from 2" time.Sleep(time.Second * 3) } }() go func() { for { select { case msg1
... See moreCaleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
Channel Direction We can specify a direction on a channel type, thus restricting it to either sending or receiving. For example, pinger’s function signature can be changed to this: func pinger(c chan<- string) Now pinger is only allowed to send to c. Attempting to receive from c will result in a compile-time error. Similarly, we can change print
... See moreCaleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
time.After creates a channel, and after the given duration, will send the current time on it (we weren’t interested in the time, so we didn’t store it in a variable).
Caleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
Buffered Channels It’s also possible to pass a second parameter to the make function when creating a channel: c := make(chan int, 1) This creates a buffered channel with a capacity of 1. Normally, channels are synchronous; both sides of the channel will wait until the other side is ready. A buffered channel is asynchronous; sending or receiving a m
... See moreCaleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
The go test command will look for any tests in any of the files in the current folder and run them. Tests are identified by starting a function with the word Test and taking one argument of type *testing.T.
Caleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
Go has the ability to automatically generate documentation for packages we write in a similar way to the standard package documentation. In a terminal, run this command: godoc golang-book/chapter8/math Average You should see information displayed for the function we just wrote: func Average(xs []float64) float64 We can improve this documentation by
... See moreCaleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
Go has rich support for concurrency using goroutines and channels.
Caleb Doxsey • Introducing Go: Build Reliable, Scalable Programs
Channels provide a way for two goroutines to communicate with each other and synchronize their execution.