Why did this happen? Please help me to analyse my 'channel' dome

Hello everybody, I’m a rookie starting learning Go. And I have a question about my demo. I can’t understand why my output will be that.In my opinion, the outputs shuold be “1,2,3…9” .Could anybody help me to explain this? Deeply Grateful.

package main

import (
	"fmt"
	"sync"
)

func main() {
	doOnve()
}

func doOnve() {
	var once sync.Once
	funBody := func() {
		fmt.Println("Only once")
	}

	c := make(chan int)

	for i:=0;i<10;i++{
		go func() {
			once.Do(funBody)
			c <- i
		}()
	}
	for i := 0; i < 10; i++ {
		fmt.Println( <- c)
	}
}

the outputs:

Gotchas and Common Mistakes with Closures in Go - Calhoun.io See where it starts " Variables declared in for loops are passed by reference"

1 Like

TL;DR: Always pass data to goroutines through function parameters.

The goroutines in your code are closures that can “see” the variables of the outer function. Usually the loop is finished before the goroutines start printing the value of the loop variable. At that point, the loop variable is already set to the final value.

Passing the values as proper function parameters avoids this situation.

go func(val int) {
		once.Do(funBody)
			c <- val
		}(i)  // note the i here

(This article explains this in more detail.)

Thank U very Muchhhh!!! :+1:

1 Like

Thank U very much!!! :+1:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.