2016-10-23 10 views
0

以下に、別の構造体を組み込む構造の例を示します。より具体的でない構造のポインタに格納するために、より具体的な構造体のポインタを渡す方法を理解しようとしています。あなたはコレクションと考えることができます。インターフェイスでのラッピングは動作しないように見えます。そうするとコピーが作成されますが、これはロック付きの構造体には有効ではありません。アイデア?golangに埋め込まれたロックを持つ汎用構造体のコレクション

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

答えて

2

Goは、構造サブタイプの概念を持っていないので、それは[]*ThignWithLockでラッピングタイプを保存することは不可能です。

あなたの主張は、インターフェイスがis incorrectのコピーになりますし、あなたが実行して所望の効果を得ることができること:

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

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

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

を限り、インターフェースは*ThingWithLockなくThingWithLockに実装されたとして、あるでしょうがありません受信側構造体自体のコピーは、構造体へのポインタだけがスタックにコピーされます。

+1

これはまさに私が探していたものです。助けてくれてありがとう! :) – EmpireJones

関連する問題