[Solved] cannot use make(IntChannel) (value of type IntChannel) as Consumer value in variable declaration


First, you declared Consumer as a chan of interface{ /* methods */ }, which most surely isn’t what you want — as a matter of fact, the error tells that you can’t assign IntChannel to it.

Then, until generics are added to the language, you don’t have a way to preserve type safety.

The closest solution to what you want to do might be adding an additional method to the interface that returns something that you can range over.

type Consumer interface {
    OpenChannel()
    CloseChannel()
    Range() <-chan interface{}
}

type IntChannel chan int

func (c IntChannel) OpenChannel() {
}

func (c IntChannel) CloseChannel() {
}

func (c IntChannel) Range() <-chan interface{} {
    ret := make(chan interface{})
    go func() {
        defer close(ret)
        for v := range c {
            ret <- v
        }
    }()
    return ret
}

func main() {
    c := make(IntChannel)
    var dataChannel Consumer = c
    go func() {
        c <- 12
        close(c)
    }()
    for data := range dataChannel.Range() {
        fmt.Println(data)
    }
}

Go1 Playground: https://play.golang.org/p/55BpISRVadE


With generics (Go 1.18, early 2022), instead you can just define a parametrized type with underlying type chan:

package main

import "fmt"

type GenericChan[T] chan T

func main() {
    c := make(GenericChan[int])
    go func() {
        c <- 12
        close(c)
    }()
    for data := range c {
        fmt.Println(data)
    }
}

Go2 Playground: https://go2goplay.golang.org/p/HQJ36ego97i

2

solved cannot use make(IntChannel) (value of type IntChannel) as Consumer value in variable declaration