我會盡量把它說清楚,首先在我的腦海里。我有一個接口和幾個通過聲明方法繼承它的類型。非常漂亮和聰明的繼承方式。然后我有一個“超級” Type Thing,所有其他類型都嵌入了它。該Thing結(jié)構(gòu)具有 Size int 和 Out chan 屬性我想理解的是為什么我可以.GetSize()從兩個子結(jié)構(gòu)中獲取 size 的值,但是我在 channel 字段上沒有同樣的成功.GetChannel()(*ndr,我用它在 goroutines 和它們的調(diào)用者之間進行通信)...我明白了 t.GetChannel undefined (type Measurable has no field or method GetChannel)它可能有助于邏輯的演示:package mainimport ( "fmt")type Measurable interface { GetSize() int}type Thing struct { Size int Out chan int}type Something struct{ *Thing }type Otherthing struct{ *Thing }func newThing(size int) *Thing { return &Thing{ Size: size, Out: make(chan int), }}func NewSomething(size int) *Something { return &Something{Thing: newThing(size)} }func NewOtherthing(size int) *Otherthing { return &Otherthing{Thing: newThing(size)} }func (s *Thing) GetSize() int { return s.Size }func (s *Thing) GetChannel() chan int { return s.Out }func main() { things := []Measurable{} pen := NewSomething(7) paper := NewOtherthing(5) things = append(things, pen, paper) for _, t := range things { fmt.Printf("%T %d \n", t, t.GetSize()) } for _, t := range things { fmt.Printf("%+v \n", t.GetChannel()) } // for _, t := range things { // fmt.Printf("%+v", t.Thing.Size) // }}注釋代碼是我正在嘗試學(xué)習(xí)的另一件事。我可以通過使用在超類型上聲明的方法來獲取值,但不能直接從子類型訪問。當然,我可以解決類型,t.(*bothTheThingTypes).Size但我失去了動態(tài)性,我沒有完全理解這個......
覆蓋 []interfaces{} 并獲取每種類型的通道字段
慕桂英3389331
2021-12-07 19:34:56