...

/

Puzzle 13 Explanation: Go Range

Puzzle 13 Explanation: Go Range

Understand how range works in Go.

We'll cover the following...

Try it yourself

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

Press + to interact
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 ...