var cache = struct {
sync.Mutex
mapping map[string]string
} {
mapping: make(map[string]string),
}
Run Code Online (Sandbox Code Playgroud)
这看起来像一个嵌入式字段sync.Mutex的结构,但我无法理解第二组括号.它编译并执行但是什么了?为什么make指令上的标签很重要(确实如此)和逗号?谢谢...
Chr*_*ski 10
你拥有的例子相当于:
type Cache struct {
sync.Mutex
mapping map[string]string
}
cache := Cache{
mapping: make(map[string]string),
}
Run Code Online (Sandbox Code Playgroud)
除了在您的示例中,您不声明类型,Cache
而是具有匿名结构.在你的例子中,与我的Cache
类型相反,类型是整个
struct {
sync.Mutex
mapping map[string]string
}
Run Code Online (Sandbox Code Playgroud)
所以想想第二对括号
cache := Cache{
mapping: make(map[string]string),
}
Run Code Online (Sandbox Code Playgroud)
部分.
make
是一个类似于C的内置函数,calloc()
它初始化一个填充了0'd值的数据结构,在Go的情况下,某些数据结构需要以这种方式初始化,其他的(大部分结构)用0'初始化d值自动.需要字段,以便编译器现在cache.mapping
是空的map[string]string
.
逗号是Go的格式的一部分,你可以Cache{mapping: make(map[string]string)}
在一行上完成所有操作,但是当字段的赋值与开始和结束括号不同时,它需要一个逗号.
归档时间: |
|
查看次数: |
886 次 |
最近记录: |