gpt4 book ai didi

go - golang 中带有嵌入式锁的通用结构集合

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

下面是一个嵌入另一个结构的示例。我试图弄清楚如何传递更具体的结构指针以存储在不太具体的结构指针中。您可以将其视为一个集合。包装在接口(interface)中似乎不起作用,因为这样做会制作副本,这对带锁的结构无效。想法?

package stackoverflow

import "sync"

type CoolerThingWithLock struct {
fancyStuff string
ThingWithLock
}

func NewCoolerThingWithLock() *CoolerThingWithLock {
coolerThingWithLock := &CoolerThingWithLock{}
coolerThingWithLock.InitThingWithLock()
return coolerThingWithLock
}

type ThingWithLock struct {
value int
lock sync.Mutex
children []*ThingWithLock
}

func (thingWithLock *ThingWithLock) InitThingWithLock() {
thingWithLock.children = make([]*ThingWithLock, 0)
}

func NewThingWithLock() *ThingWithLock {
newThingWithLock := &ThingWithLock{}
newThingWithLock.InitThingWithLock()
return newThingWithLock
}

func (thingWithLock *ThingWithLock) AddChild(newChild *ThingWithLock) {
thingWithLock.children = append(thingWithLock.children, newChild)
}

func (thingWithLock *ThingWithLock) SetValue(newValue int) {
thingWithLock.lock.Lock()
defer thingWithLock.lock.Unlock()

thingWithLock.value = newValue

for _, child := range thingWithLock.children {
child.SetValue(newValue)
}
}

func main() {
thingOne := NewThingWithLock()
thingTwo := NewCoolerThingWithLock()
thingOne.AddChild(thingTwo)

thingOne.SetValue(42)
}

Error: cannot use thingTwo (type *CoolerThingWithLock) as type *ThingWithLock in argument to thingOne.AddChild

最佳答案

不可能将包装类型存储在 []*ThignWithLock 中,因为 go 没有结构子类型的概念。

您断言接口(interface)将导致复制 is incorrect ,您可以通过执行以下操作获得所需的效果:

type InterfaceOfThingThatParticipatesInAHierarchy interface {
AddChild(InterfaceOfThingThatParticipatesInAHierarchy)
SetValue(int)
}

type ThingWithLock struct {
...
children []InterfaceOfThingThatParticipatesInAHierarchy
}

func (thingWithLock *ThingWithLock) AddChild(newChild InterfaceOfThingThatParticipatesInAHierarchy) { ... }

只要接口(interface)是在 *ThingWithLock 而不是 ThingWithLock 上实现的,就不会复制接收器结构本身,只有指向结构的指针会被复制到栈上。

关于go - golang 中带有嵌入式锁的通用结构集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207878/

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