遍历 []interfaces{} 并获取每种类型的通道字段

range over an []interfaces{} and get the channel field of each type

我会先在脑海中尽可能清楚地说明。

我有一个接口和几个通过声明方法继承它的类型。非常漂亮和聪明的继承方式。

然后我有一个 "super" 类型 Thing,所有其他类型都嵌入了它。

Thing 结构有一个 Size int 和一个 Out chan 属性

我想了解的是为什么我可以从两个子结构中获得大小 .GetSize() 的值,但我在通道字段 .GetChannel() 上却没有同样的成功(*ndr,我用它来在 goroutines 和它们的调用者之间进行通信)

...这里我得到 t.GetChannel undefined (type Measurable has no field or method GetChannel)

它可能有助于逻辑演示:

package main

import (
    "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)
    // }
}

注释代码是我正在努力学习的另一件事。我可以通过使用在超类型上声明的方法来获取值,但不能通过直接从子类型访问来获取值。当然,我可以用 t.(*bothTheThingTypes).Size 解析类型,但我失去了动态性,我没有完全理解这个...

What I'm trying to understand is why I can get the value of size .GetSize() from both the child structs, but I don't have the same success with the channel field .GetChannel()

type Measurable interface {
    GetSize() int
}

...

things := []Measurable{}
for _, t := range things {
    fmt.Printf("%+v \n", t.GetChannel())
}

我可能忽略了重点,但这似乎完全是由于您的 Measurable 界面没有 GetChannel 方法。