使用带有匿名函数的标签

huangapple go评论83阅读模式
英文:

using a label with anonymous function

问题

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

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 stack trace包的第103行,有一个匿名函数定义在sync pool结构体内,如下所示,带有New:标签:

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

根据源代码中的注释,我猜测Facebook包已经“指定了一个函数,在Get返回nil时生成一个值”,但为什么要这样定义New:呢?

英文:

There's a New function inside a Pool struct in the source code of the sync package that's defined like this

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{}
}

At line 103 of a golang stack trace package created by Facebook, there's an anonymous function defined inside a sync pool struct like this with the New: label:

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

So, going from the comments in the source code, I'm assuming that the Facebook package has "specified a function to generate a value when Get would otherwise return nil," but why might it be defined with New: like this?

答案1

得分: 2

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,
}
英文:

New isn't a label, it's a field name in a 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
}

It's no different than N in the following example

type T struct {
	N int
}

t := T{
	N: 1,
}

huangapple
  • 本文由 发表于 2014年11月18日 22:14:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/26996410.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定