繁体   English   中英

使用带有匿名功能的标签

[英]using a label with anonymous function

sync包的源代码中的Pool结构内部有一个New函数,其定义如下:

type Pool struct {
local unsafe.Pointer // local fixed-size per-P pool, actual type is [P]poolLocal
localSize uintptr // size of the local array
// New optionally specifies a function to generate
// a value when Get would otherwise return nil.
// It may not be changed concurrently with calls to Get.
New func() interface{}
}

在Facebook创建的golang堆栈跟踪包的第103行中,在这样的同步池结构中定义了一个匿名函数,带有New:标签:

var pcsPool = sync.Pool{
    New: func() interface{} {
        return make([]uintptr, maxStackSize)
    },
}

因此,从源代码中的注释出发,我假设Facebook包已“指定了一个函数,当Get否则将返回nil时将生成一个值”,但是为什么要用New:来定义它New:

New不是标签,而是sync.Pool的字段名称。

type Pool struct {

        // New optionally specifies a function to generate
        // a value when Get would otherwise return nil.
        // It may not be changed concurrently with calls to Get.
        New func() interface{}
        // contains filtered or unexported fields
}

在下面的示例中与N没什么不同

type T struct {
    N int
}

t := T{
    N: 1,
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM