Home > Backend Development > Golang > Why Does sync.WaitGroup Have an Empty Method Set, Yet Its Methods Appear Callable on Non-Pointer Values?

Why Does sync.WaitGroup Have an Empty Method Set, Yet Its Methods Appear Callable on Non-Pointer Values?

DDD
Release: 2024-11-23 14:25:14
Original
840 people have browsed it

Why Does sync.WaitGroup Have an Empty Method Set, Yet Its Methods Appear Callable on Non-Pointer Values?

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template