concurrency
var wg sync.WaitGroup
results := make(chan int, 3)
for _, n := range []int{1, 2, 3} {
wg.Add(1)
go func(v int) {
defer wg.Done()
results <- v * 2
}(n)
}
go func() { wg.Wait(); close(results) }()
That ran and produced a sum of twelve
Pass the value
The goroutine takes v as an argument
Capturing the loop variable directly was a bug in older versions
Passing it explicitly stays correct everywhere
Closing channels
Only the sender closes
Closing from the receiver causes a panic
for range over a channel ends when it is closed
Buffering
A buffered channel absorbs a few sends It is not a substitute for a consumer An unbuffered channel is synchronous and often the right default
Leaks
A goroutine blocked forever on a channel is a leak Go 1.27 promotes the goroutine leak profile to general availability Use it when a long running service slowly loses memory
Next
Files in 07 filesystem
Posted