Home >Backend Development >Golang >Why Can I Call sync.WaitGroup Methods on Values, Not Just Pointers?

Why Can I Call sync.WaitGroup Methods on Values, Not Just Pointers?

Barbara Streisand
Barbara StreisandOriginal
2024-12-16 07:44:09532browse

Why Can I Call sync.WaitGroup Methods on Values, Not Just Pointers?

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:

  • [Calling a method with a pointer receiver by an object instead of a pointer to it?](https://stackoverflow.com/questions/4239271)

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!

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