type fun struct {}
type starcraft struct {
*fun // embedding struct
mu sync.Mutex
}
我知道我可以将 initial struct startcraft 写成:
f := &fun{}
s := starcraft{f, *new(sync.Mutex)}
我不喜欢它,因为:
一个。我不想自己初始化 sync.Mutex
在这种情况下,使用 *new(sync.Mutex) 会浪费副本。
有没有更好的方法?
最佳答案
您可以命名嵌入式结构:
s := starcraft{
fun: f,
mu: *new(sync.Mutex),
}
您不需要使用 new
来创建零值。如果类型已经声明,则根本不需要对其进行初始化,也可以使用零值。
s := starcraft{
fun: f,
mu: sync.Mutex{},
}
并且由于 Mutex 的零值是有效的、未锁定的 Mutex ( http://golang.org/pkg/sync/#Mutex ),您绝对不需要初始化它,并且可以将它从结构文字中删除。
s := starcraft{
fun: f,
}
最重要的是,嵌入 Mutex 并直接在外部结构上调用 Lock
和 Unlock
也很常见。
关于go - 具有多个字段的嵌入式结构的文字初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24785738/