英文:
literal initialization of embeded struct with multiple fields
问题
你好,以下是翻译好的内容:
type fun struct {}
type starcraft struct {
*fun // 嵌入结构体
mu sync.Mutex
}
我知道我可以使用字面值初始化 starcraft 结构体:
f := &fun{}
s := starcraft{f, *new(sync.Mutex)}
但我不喜欢这种方式,因为:
a. 我不想自己初始化 sync.Mutex
b. 在这种情况下,使用 *new(sync.Mutex) 会产生一个多余的副本。
有更好的方法吗?
英文:
type fun struct {}
type starcraft struct {
*fun // embedding struct
mu sync.Mutex
}
I know I can literal initial struct startcraft as:
f := &fun{}
s := starcraft{f, *new(sync.Mutex)}
I don't like it, since:
a. I don't want to initialize sync.Mutex by myself
b. in this case there is a wasted copy using *new(sync.Mutex).
Is there any better way?
答案1
得分: 5
你可以给嵌入的结构体命名:
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
也是非常常见的做法。
英文:
You can name embedded structs:
s := starcraft{
fun: f,
mu: *new(sync.Mutex),
}
You don't need to use new
to create a zero value. If the type is already declared, you don't need to initialize it at all, or you can use the zero value.
s := starcraft{
fun: f,
mu: sync.Mutex{},
}
And since the zero value for a Mutex is a valid, unlocked Mutex (http://golang.org/pkg/sync/#Mutex), you definitely don't need to initialize it, and can leave it out of the struct literal.
s := starcraft{
fun: f,
}
On top of that, it's also very common to embed the Mutex and call Lock
and Unlock
directly on the outer struct.
答案2
得分: 2
嵌入结构体可以被命名,这意味着可以使用以下方法:
f := &fun{}
s := starcraft{fun: f}
这可能是你想要的。
英文:
Embedded structs can be named, which suggests this method
f := &fun{}
s := starcraft{fun:f}
Which might be what you want
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论