Friday, June 28, 2024
HomeGolangCompletely different outcome when utilizing for loops on channels - Getting Assist

Completely different outcome when utilizing for loops on channels – Getting Assist


Hello, I’m studying channels proper now. I seen after I use for loop 3 elements, the result’s 1 2. However with for loop vary, I bought the specified outcome, 1 2 3 4.

bundle major

import (
	"fmt"
)

func major() {
	ch := make(chan int, 4)

	ch <- fetchValue(1)
	ch <- fetchValue(2)
	ch <- fetchValue(3)
	ch <- fetchValue(4)

	shut(ch)

	for vary len(ch) {
		outcome := <-ch
		fmt.Println(outcome) // 1 2 3 4
	}


	for i := 0; i < len(ch); i++ {
		outcome := <-ch
		fmt.Println(outcome) // 1 2
	}

}

func fetchValue(v int) int {
	return v
}

May somebody clarify why that occurred? A hyperlink for references can be useful. Thanks.

Within the second for loop len(ch) modifications with every iteration since you are emptying the channel. So, by the point you get to 2, you already consumed two parts from the channel and now len(ch) == 2 and i == 2.

Which line instructs it to empty the channel? Do you may have an instance to supply related outcomes or something to enhance my understanding relating to this sort of habits? I’m completely confused about it. Thanks.

Edit
After debugging, it’s right that the channel is emptied the second after I obtained it outcome := <-ch

Thanks for the reason. A lot appreciated.

Only for completeness, your vary loop might be simplified to be:

	for outcome := vary ch {
		fmt.Println(outcome) // 1 2 3 4
	}

For the reason that channel is closed, the loop will exit when it has completed studying all of the values out of the channel.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments