Home  >  Article  >  Backend Development  >  Why Can sync.WaitGroup Methods Be Called on Non-Pointer Values?

Why Can sync.WaitGroup Methods Be Called on Non-Pointer Values?

Linda Hamilton
Linda HamiltonOriginal
2024-11-24 02:57:10545browse

Why Can sync.WaitGroup Methods Be Called on Non-Pointer Values?

Method Set of sync.WaitGroup

The sync.WaitGroup is a synchronization primitive that enables you to wait for a collection of goroutines to complete. While its documentation suggests that the Add, Done, and Wait methods require a pointer receiver, you can also use them on non-pointer values. How is this possible?

The secret lies in the empty method set of sync.WaitGroup. This means that all the methods of sync.WaitGroup are pointer receivers. When you create a value of type sync.WaitGroup, such as:

var wg sync.WaitGroup

You are actually creating a pointer to a sync.WaitGroup struct. This pointer is automatically dereferenced when you call methods on the wg variable. For instance, the following code compiles successfully:

wg.Add(1)
wg.Done()
wg.Wait()

The Go compiler implicitly converts wg to a pointer to sync.WaitGroup before calling the methods. This behavior is defined in the Go language specification:

If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m().

Therefore, you can call methods that have pointer receivers on non-pointer values if those values are addressable. Non-pointer values are always addressable in Go.

The above is the detailed content of Why Can sync.WaitGroup Methods Be Called on Non-Pointer Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn