douyou1901 2017-06-07 18:41
浏览 428

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

  • 写回答

1条回答 默认 最新

  • dongtan9066 2017-06-07 19:00
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算