Search code examples
gochanneltype-assertion

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


I'll try to make it as clear as possible, in my head first.

I have an interface and a couple of Types that inherit it by declaring a method. Pretty nice and clever way of inheritance.

I have then a "super" Type Thing, which all the other Types embed.

The Thing struct has a Size int and an Out chan properties

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() (*ndr which I'm using to communicate among goroutines and their caller)

...here I get t.GetChannel undefined (type Measurable has no field or method GetChannel)

It might help a demo of the logic:

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)
    // }
}

The commented code is another thing I'm trying to learn. I can get a value by using a method declared on the super Type, but not by accessing directly from the child one. Sure, I could resolve the type with t.(*bothTheThingTypes).Size but I lose the dinamicity, I'm not fully getting this...


Solution

  • 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())
    }
    

    I may be missing the point but this seems to be caused strictly by the fact that your Measurable interface doesn't have a GetChannel method.