1 min read

range over channels in go - Fibonacci example

range over channels in go - Fibonacci example


This sequence of numbers occurs in nature, and has many uses.

In a Fibonacci sequence, each number is equal to the previous two numbers added together.

Fibonacci numbers are easily computed in modern programming languages.

This computational task helps us learn about how a channel works in go and how the range keyword can help make more complex tasks easier.

package main
import "fmt"
func Fibonacci(ch chan int, count int) {
    f2, f1 := 0, 1
    for count >= 0 {
        ch <- f2
        f2, f1 = f1, f2+f1
func main() {
    ch := make(chan int)
    go Fibonacci(ch, 10)
    i := 0
    for num := range ch {
        fmt.Printf("F(%d): \t%d\n", i, num)

There you have it, a very basic go program.

In our main func we first allocate a channel, and pass it into our Fibonacci func along with an argument of 10 telling Fibonacci to produce 10 numbers from the Fibonacci sequence.

Next we range over the channel and print any values that channel produces for as long as it is not closed.

In our Fibonacci function we simply declare a few variables to hole our default values for the first number in our Fibonacci sequence, then we for loop as many iterations as we were provided in our second argument (in this example it was 10).

In each loop we send to the channel our current number in the sequence, decrement our counter, and calculate the next number in the sequence. We do this until our counter reaches zero and the last calculated number in the sequence has been sent through the channel.