Why Can sync.WaitGroup Methods Be Called on Values Instead of Pointers?
Despite the sync.WaitGroup documentation indicating that its methods require a *sync.WaitGroup receiver, it is possible to call these methods on values of type sync.WaitGroup. This is because all sync.WaitGroup methods have pointer receivers, meaning that the compiler will automatically convert the value to a pointer when the method is called.
The Empty Method Set of sync.WaitGroup
The actual method set of a sync.WaitGroup is empty. To confirm this, you can use reflection:
wg := sync.WaitGroup{} fmt.Println(reflect.TypeOf(wg).NumMethod()) // Output: 0
Therefore, the methods that appear to be defined on sync.WaitGroup values are actually part of the method set of *sync.WaitGroup.
Shorthand Notation for Calling Pointer Methods on Values
When you call a pointer method on a value, the compiler translates it to a call on the pointer to that value. For example:
var wg sync.WaitGroup wg.Add(1)
Is equivalent to:
(&wg).Add(1)
The Spec for Go states that if a variable is addressable and its method set contains a method, calling that method directly on the variable is shorthand for calling it on the pointer to that variable.
Related Question
For more information on this topic, refer to the related question:
The above is the detailed content of Why Can I Call sync.WaitGroup Methods on Values, Not Just Pointers?. For more information, please follow other related articles on the PHP Chinese website!