Search⌘ K

Puzzle 13 Explanation: Go Range

Explore how to use Go's range keyword with channels to consume values properly. Learn why closing channels is essential to avoid goroutine leaks and understand best practices for managing goroutines in Go programming puzzles.

We'll cover the following...

Try it yourself

Try executing the code below to see the result for yourself.

Go (1.16.5)
package main
import (
"fmt"
)
func fibs(n int) chan int {
ch := make(chan int)
go func() {
a, b := 1, 1
for i := 0; i < n; i++ {
ch <- a
a, b = b, a+b
}
}()
return ch
}
func main() {
for i := range fibs(5) {
fmt.Printf("%d ", i)
}
fmt.Println()
}

Explanation

To obtain a value from a channel, we can either use the receive operator (←ch) or do a for loop with a ...