Channel returns the same value twice on receive

Issue

Hello I have the following simple program:
I have a function printNums(nums chan int) which should take 3 numbers from a channel and print them concurrently. Each printing is done in a new goroutine inside the range statement.
However when I run this program, instead of expected output 4, 12, 32, i get 12, 12, 32. Can you help me find out where is the problem and why i don’t receive from channel same values that have been sent to channel? Thank you.

package main

import ("fmt")

func printNums(nums chan int){
    c := make(chan struct{}, 100)
        for num := range(nums){
            go func(){
                fmt.Println(num)
                c <- struct{}{}
            }()
        }
    <-c
    <-c
    <-c
}
func main(){
    nums := make(chan int)

  go func() {
      nums <- 4
      nums <- 12 
      nums <- 32 
      close(nums)
  }()

  printNums(nums)
}

Solution

You are printing the current value of num instead of the value num was when the goroutine was created. The loop variable is overwritten at every turn, and the goroutine may see the updated value.

for num := range(nums){
    go func(x int){
         fmt.Println(x)
         c <- struct{}{}
    }(num)
 }

Answered By – Burak Serdar

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.