[英]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.