[英]What are the second pair of braces in this Golang struct?
var cache = struct {
sync.Mutex
mapping map[string]string
} {
mapping: make(map[string]string),
}
这看起来像一个嵌入式字段sync.Mutex的结构,但我无法理解第二组括号。 它编译并执行但是什么了? 为什么make指令上的标签很重要(确实如此)和逗号? 谢谢...
你拥有的例子相当于:
type Cache struct {
sync.Mutex
mapping map[string]string
}
cache := Cache{
mapping: make(map[string]string),
}
除了在您的示例中,您不要声明一种类型的Cache
,而是使用匿名结构。 在您的示例中,与我的Cache
类型相反,类型是整个
struct {
sync.Mutex
mapping map[string]string
}
所以想想第二对括号
cache := Cache{
mapping: make(map[string]string),
}
部分。
make
是一个内置函数,类似于C的calloc()
,它初始化一个填充了0'd值的数据结构,在Go的情况下,某些数据结构需要以这种方式初始化,其他的(大部分结构)是自动初始化为0'd值。 需要字段,以便编译器现在的cache.mapping
是一个空map[string]string
。
逗号是Go的格式的一部分,你可以在一行上执行Cache{mapping: make(map[string]string)}
,但是当字段的赋值与开始和结束括号不同时,它需要一个逗号。
这被称为“struct literal”或“anonymous struct”,事实上,你总是如何在Go中创建结构,它可能不会立即显而易见,因为你可能习惯于为结构类型创建新类型来进行声明他们不那么冗长。
整个struct定义实际上是Go中的一个类型,就像int
或[]byte
或string
。 就像你能做的那样:
type NewType int
var a NewType = 5 // a is a NewType (which is based on an int)
要么:
a := 5 // a is an int
并且两者都是看起来像int的不同类型,你也可以用结构做同样的事情:
// a is type NewType (which is a struct{}).
type NewType struct{
A string
}
a := NewType{
A: "test string",
}
// a is type struct{A string}
a := struct{
A string
}{
A: "test string",
}
类型名称( NewType
)刚刚被结构本身的类型struct{A string}
所取代。 请注意,它们不是用于比较或赋值的类型(别名),但它们共享相同的语义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.