drwn65609 2017-02-27 04:41
浏览 34
已采纳

`sync.WaitGroup`的方法是什么?

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?

  • 写回答

3条回答 默认 最新

  • dsjmrpym220113739 2017-02-27 08:12
    关注

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题