英文:
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,
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论