Range for loop over an unBuffered Channel

Issue

I’m new to golang and going over the gotour. I have following code which works perfectly as it should.

package main

import (
    "fmt"
)

func fibonacci(n int, c chan int) {
    x, y := 0, 1
    for i := 0; i < n; i++ {
        c <- x
        x, y = y, x+y
    }
    close(c)
}

func main() {
    c := make(chan int, 5)
//  c := make(chan int)     //doesn't work, why ?
    go fibonacci(cap(c), c)
    for i := range c {
        fmt.Println(i)
    }
}

But when I use an unbuffered channel instead of a buffered one, I don’t get any output, why’s that so ?

Solution

When you pass cap(c) through to the fibonacci function, what value is passed through? on the buffered channel the n == 5, on the unbuffered channel n == 0

and your for loop

for i := 0; i < 0; i++ {

Actually, this is a really bad way of handling the situation. You are requiring the number of channels to be equal to the number of iterations.

Using a channel in this way I would not recommend, think of the channel as being able to operate concurrently, which is not something you would want to do in this scenario!

If you pass the number in separately to the number of routines, then the unbuffered channel will work as expected:

https://play.golang.org/p/G1b2vjTUCsV

Answered By – Raymond Jones

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.