Method Set of sync.WaitGroup
When working with Golang's sync.WaitGroup, one may encounter the question of its method set.
The Solution
-
Empty Method Set:
The method set of sync.WaitGroup is technically empty. This means that its methods cannot be directly invoked on non-pointer values.
-
Pointer Receivers:
All methods of sync.WaitGroup have pointer receivers, effectively making them part of the method set of the pointer type, *sync.WaitGroup.
The Reason
-
Automatic Dereferencing:
Despite the pointer receiver requirement, calls to sync.WaitGroup methods on non-pointer values are possible due to automatic dereferencing.
-
Shorthand Notation:
In such cases, the compiler implicitly takes the address of the non-pointer value and uses it as the method receiver. This effectively translates wg.Add(1) to (&wg).Add(1).
Example
In the provided code snippet, wg is declared as a value of type sync.WaitGroup. The subsequent method calls (wg.Add, wg.Done, etc.) are allowed because the compiler automatically dereferences wg and treats it as a pointer.
Related Question
Refer to the following question for further understanding:
- Calling a method with a pointer receiver by an object instead of a pointer to it?
The above is the detailed content of Why Does sync.WaitGroup Have an Empty Method Set, Yet Its Methods Appear Callable on Non-Pointer Values?. For more information, please follow other related articles on the PHP Chinese website!