duanhai1455 2016-10-23 21:15
浏览 29
已采纳

Golang中带有嵌入式锁的泛型结构的集合

Below I have an example of one structure which embeds another. I'm trying to figure out how to pass the more specific structure pointer to be stored in a less specific one. You can think of it as a collection. Wrapping in an interface doesn't seem to work, as doing so would make a copy, which isn't valid for structs with locks. Ideas?

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

  • 写回答

1条回答 默认 最新

  • dounue1965 2016-10-23 21:36
    关注

    It's impossible to store the wrapping type in []*ThignWithLock since go has no notion of structural subtyping.

    Your assertion that an interface will result in copying is incorrect, and you can get the desired effect by doing:

    type InterfaceOfThingThatParticipatesInAHierarchy interface {
        AddChild(InterfaceOfThingThatParticipatesInAHierarchy)
        SetValue(int)
    }
    
    type ThingWithLock struct {
        ...
        children []InterfaceOfThingThatParticipatesInAHierarchy
    }
    
    func (thingWithLock *ThingWithLock) AddChild(newChild InterfaceOfThingThatParticipatesInAHierarchy) { ... }
    

    As long as the interface is implemented on a *ThingWithLock and not ThingWithLock, there will be no copying of the receiver struct itself, only the pointer to the struct will be copied on the stack.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分