golang initialize member with struct itself for sync.Mutex and sync.Cond

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

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

huangapple
  • 本文由 发表于 2017年6月8日 02:41:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/44420451.html
匿名

发表评论

匿名网友

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

确定