gpt4 book ai didi

golang 使用结构本身为 sync.Mutex 和 sync.Cond 初始化成员

转载 作者:数据小太阳 更新时间:2023-10-29 03:04:35 32 4
gpt4 key购买 nike

这是代码:

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

此代码编译失败:

sync.Mutex (type) is not an expression

所以基本上问题是如何在初始化时引用结构本身(因为它有一个嵌入式成员 sync.Mutex)? (例如,c++ 有 this)。

最佳答案

可以先新建一个实例,然后再引用嵌入字段:

type SomeThing struct {
sync.Mutex
cv *sync.Cond
num int
}

func NewSomething() *SomeThing {
st := &SomeThing{}
st.cv = sync.NewCond(&st.Mutex)
return st
}

在这里玩:https://play.golang.org/p/BlnHMi1EKT

关于golang 使用结构本身为 sync.Mutex 和 sync.Cond 初始化成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44420451/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com