嵌套结构的字面初始化,其中包含多个字段。

huangapple go评论87阅读模式
英文:

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嵌入并直接在外部结构体上调用LockUnlock也是非常常见的做法。

英文:

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}

这可能是你想要的。

Playground

英文:

Embedded structs can be named, which suggests this method

f := &fun{}
s := starcraft{fun:f}

Which might be what you want

Playground

huangapple
  • 本文由 发表于 2014年7月17日 00:16:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/24785738.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定