Home >Backend Development >Golang >Why Use Pointers and Variables with Go\'s WaitGroup?
WaitGroup Reference: Using Pointers and Variables
The WaitGroup in Go provides synchronization primitives for coordinating goroutines. It has three primary functions: Add, Done, and Wait. Here, we'll examine their usage and why they may be called using both pointers and variables.
WaitGroup Methods
As mentioned, all WaitGroup functions are called by a pointer to a WaitGroup, denoted by the *WaitGroup receiver type. This allows them to modify the internal state of the WaitGroup, tracking goroutine completion and waiting for them to finish.
Understanding Usage
The code snippet in question shows both pointer and variable usage for WaitGroup functions:
func main() { // Declared as a variable var wg sync.WaitGroup // Called with a pointer to the WaitGroup wg.Add(1) // Called with a variable (not a pointer) go worker(i, wg) }
Passing a Pointer to the Worker
When passing the WaitGroup to the worker goroutine, it's crucial to pass its address using &. This is because the worker's Done function operates on the WaitGroup pointer, and passing it directly as a variable would create a copy, resulting in unexpected behavior.
Conclusion
In summary, all WaitGroup methods are designed to be called with a pointer receiver. Variables are used in the code snippet to simplify declaration and function calling. However, when passing the WaitGroup to goroutines, it's essential to pass its address (&) to ensure that all methods operate on the same underlying pointer.
The above is the detailed content of Why Use Pointers and Variables with Go\'s WaitGroup?. For more information, please follow other related articles on the PHP Chinese website!