Goroutine Communication with Channels - Go Tutorial for Beginners #25 -
Video: Goroutine Communication with Channels - Go Tutorial for Beginners #25 - by Taught by Celeste AI - AI Coding Coach
Watch full page →Goroutine Communication with Channels in Go
Channels in Go provide a powerful way to communicate and synchronize between goroutines. This tutorial covers how to create channels, send and receive data, use buffered channels, close channels properly, and iterate over channel data with range.
Code
package main
import (
"fmt"
"time"
)
func worker(ch chan string) {
// Send a message to the channel
ch <- "Hello from goroutine"
// Close the channel to signal no more values will be sent
close(ch)
}
func main() {
// Create an unbuffered channel of strings
ch := make(chan string)
// Start a goroutine that sends data into the channel
go worker(ch)
// Receive data from the channel until it is closed
for msg := range ch {
fmt.Println(msg)
}
// Buffered channel example
bufCh := make(chan int, 2) // buffer size 2
bufCh <- 1
bufCh <- 2
// The following send would block if buffer is full, so we receive first
fmt.Println(<-bufCh)
fmt.Println(<-bufCh)
// Demonstrate sending and receiving with arrow operators
go func() {
for i := 0; i < 3; i++ {
bufCh <- i * 10
fmt.Println("Sent", i*10)
}
close(bufCh)
}()
// Receive from buffered channel until closed
for val := range bufCh {
fmt.Println("Received", val)
}
// Give goroutines time to finish before main exits
time.Sleep(time.Second)
}
Key Points
- Channels allow safe communication and synchronization between goroutines using send (<-) and receive (<-) operations.
- Unbuffered channels block sends until a receiver is ready, while buffered channels allow limited asynchronous sends.
- Closing a channel signals no more values will be sent and allows receivers to detect completion using range or the second boolean value.
- Using range over a channel receives values until the channel is closed, simplifying iteration in concurrent pipelines.
- Channels are fundamental for building concurrent patterns and pipelines in Go programs.