什么是`sync.WaitGroup`的方法集? [英] What is the method set of `sync.WaitGroup`?

查看:127
本文介绍了什么是`sync.WaitGroup`的方法集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有这个简单的程序:

  package main 

import(
fmt
sync
time


var wg sync.WaitGroup

func main(){
wg.Add(1)

去func(){
fmt.Println(starting ...)
time.Sleep(1 * time.Second)$ ()
wg.Done()
}()

wg.Wait()
$ b(done ....)b $ b fmt.Println
$ b

请注意,我使用 var wg sync.WaitGroup 作为一个值,而不是一个指针。但是同步软件包的页面指定 Add 完成等待函数带一个 * sync.WaitGroup



为什么/这是如何工作的?

解决方案

方法集 rel =nofollow noreferrer> sync.WaitGroup 是空方法集:

  wg:= sync.WaitGroup {} 
fmt.Println(reflect.TypeOf(wg).NumMethod())

输出(在 Go Playground < a>):

  0 

这是因为 sync.WaitGroup 的所有方法都有指针接收器,所以它们都是<$ c $的方法集的一部分

<$ p $ (1)
wg.Done()
//等等



$ b wg.Add code>

这实际上是一个简写(& wg).Add(1)(& wg).Done() p>

这是规格:通话:
$ b


如果 x 是可寻址的,并且& x 的方法集包含 m xm()(& x).m()


所以当你有一个可寻址的值(一个变量是可寻址的),你可以调用任何具有指针接收器的非指针值的方法,编译器会自动获取地址并将其作为接收器值使用。



请参阅相关问题:

通过一个对象而不是一个指针调用一个指针接收器的方法吗?


I have this simple program below

package main

import (
    "fmt"
    "sync"
    "time"
)

var wg sync.WaitGroup

func main() {
    wg.Add(1)

    go func() {
        fmt.Println("starting...")
        time.Sleep(1 * time.Second)
        fmt.Println("done....")
        wg.Done()
    } ()

    wg.Wait()

}

Notice that I use var wg sync.WaitGroup as a value, not a pointer. But the page for the sync package specifies that the Add, Done and Wait function take a *sync.WaitGroup.

Why/How does this work?

解决方案

The method set of sync.WaitGroup is the empty method set:

wg := sync.WaitGroup{}
fmt.Println(reflect.TypeOf(wg).NumMethod())

Output (try it on the Go Playground):

0

This is because all the methods of sync.WaitGroup have pointer receivers, so they are all part of the method set of the *sync.WaitGroup type.

When you do:

var wg sync.WaitGroup

wg.Add(1)
wg.Done()
// etc.

This is actually a shorthand for (&wg).Add(1), (&wg).Done() etc.

This is in Spec: Calls:

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

So when you have a value that is addressable (a variable is addressable), you may call any methods that have pointer receiver on non-pointer values, and the compiler will automatically take the address and use that as the receiver value.

See related question:

Calling a method with a pointer receiver by an object instead of a pointer to it?

这篇关于什么是`sync.WaitGroup`的方法集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆