golang的初始化成员具有struct本身,用于sync.Mutex和sync.Cond

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).

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