英文:
golang initialize member with struct itself for sync.Mutex and sync.Cond
问题
以下是翻译好的内容:
这是一段Go代码:
type someThing struct {
sync.Mutex
cv *sync.Cond
num int
}
func NewSomething() *someThing {
// 你该如何做这个?
return &someThing{cv: sync.NewCond(&sync.Mutex{})}
}
这段代码无法编译:
sync.Mutex (type) is not an expression
所以基本上问题是如何在初始化结构体时引用结构体本身(因为它有一个嵌入的成员sync.Mutex)?(例如,C++中有this)。
英文:
Here is go code:
type someThing struct {
sync.Mutex
cv *sync.Cond
num int
}
func NewSomething() *someThing {
// how do you do this ?
return &someThing{cv:sync.NewCond(sync.Mutex)}
}
This code fails to compile:
sync.Mutex (type) is not an expression
So basically the question is how to refer to the struct itself (because it has an embedded member sync.Mutex) while initializing it ? (c++ has this, for example).
答案1
得分: 2
你可以先创建一个新的实例,然后引用嵌入字段:
type SomeThing struct {
sync.Mutex
cv *sync.Cond
num int
}
func NewSomething() *SomeThing {
st := &SomeThing{}
st.cv = sync.NewCond(&st.Mutex)
return st
}
在这里可以运行Go代码:https://play.golang.org/p/BlnHMi1EKT
英文:
You can create a new instance first, and then refer to the embedded field:
type SomeThing struct {
sync.Mutex
cv *sync.Cond
num int
}
func NewSomething() *SomeThing {
st := &SomeThing{}
st.cv = sync.NewCond(&st.Mutex)
return st
}
GoPlay here: https://play.golang.org/p/BlnHMi1EKT
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论