Go by Example: Channels
Understand Channels, the conduits that connect concurrent goroutines. This example demonstrates how to send and receive values to synchronize execution and share data safely without explicit locks, following Go's philosophy: "Do not communicate by sharing memory; instead, share memory by communicating."
Code
package main
import "fmt"
func main() {
// Create a new channel of strings
messages := make(chan string)
// Send to channel in a goroutine
go func() {
messages <- "ping"
}()
// Receive from channel
msg := <-messages
fmt.Println(msg)
}Explanation
Channels are the pipes that connect concurrent goroutines. You can send values into channels from one goroutine and receive those values into another goroutine. This mechanism allows for safe communication and synchronization without explicit locks.
Create a new channel with make(chan val-type). Channels are typed by the values they convey. By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.
Key channel operations:
- ch <- v // Send v to channel ch
- v := <-ch // Receive from ch, and assign value to v
- close(ch) // Close the channel

