Lesson 14 of 60 · Go
Channels: Communication Between Goroutines
Duration: 20 minutes
Channels
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
Channels are typed conduits that allow goroutines to communicate safely.
ch := make(chan int) // unbuffered channel
go func() { ch <- 42 }() // send
val := <-ch // receive
fmt.Println(val) // 42
Buffered channels
buf := make(chan string, 3) // capacity 3
buf <- "a"
buf <- "b"
fmt.Println(<-buf) // a
Closing channels
close(buf)
for v := range buf { fmt.Println(v) }
Select statement (multiplexing)
select {
case v := <-ch1:
fmt.Println("from ch1", v)
case ch2 <- 99:
fmt.Println("sent to ch2")
default:
fmt.Println("no activity")
}