Channel Basics
Unbuffered and buffered channels, channel direction, range, and close.
package main
import "fmt"
func main() {
// Unbuffered: sender blocks until receiver is ready
ch := make(chan string)
go func() {
ch <- "hello from goroutine"
}()
fmt.Println(<-ch)
// Buffered: sender doesn't block until buffer is full
buf := make(chan int, 3)
buf <- 1
buf <- 2
buf <- 3
fmt.Println(<-buf, <-buf, <-buf)
// Range over channel
nums := make(chan int)
go func() {
for i := 0; i < 5; i++ {
nums <- i
}
close(nums)
}()
for n := range nums {
fmt.Println("received:", n)
}
// Channel direction in functions
out := make(chan string, 1)
send(out, "typed channels")
fmt.Println(receive(out))
}
func send(ch chan<- string, msg string) { ch <- msg }
func receive(ch <-chan string) string { return <-ch }