Sharing Variables in Go: Understanding the Difference Between Two Cases
In Go, goroutines are lightweight concurrent tasks that can share memory and communicate using channels. Variable sharing among goroutines requires careful handling to avoid data race issues.
Consider the following Go program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
When executed, this program prints the expected output:
1 2 3 4 5 |
|
In this case, each goroutine has its own copy of the variable x, which is initialized with the current value of i when the goroutine is created. This is because x is declared within the anonymous function, and its scope is limited to that function.
Now, consider a slight modification to the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
This time, the output becomes:
1 2 3 4 5 |
|
The explanation lies in the way the variable i is used in the goroutine. Since i is declared outside the anonymous function, it's shared among all goroutines. In this case, when each goroutine executes fmt.Println(i), it's printing the final value of i, which is 5.
To verify this, we can add printing of the memory addresses of x and i within the goroutines. The output shows that x has different addresses for each goroutine, while i has the same address for all goroutines:
1 2 3 4 5 6 |
|
In conclusion, the difference in variable sharing between the two cases arises from the scope of the variable declared in the anonymous function. When a variable is declared within the anonymous function, it's private to that goroutine. On the other hand, a variable declared outside the anonymous function is shared among all goroutines.
The above is the detailed content of Why does sharing variables in Go lead to different outputs depending on their scope within anonymous functions?. For more information, please follow other related articles on the PHP Chinese website!