如何在 golang 中跨未知类型的通道进行范围



我有一个函数,它接收一个字符串,并基于字符串值创建一个类型的通道。然后发送此通道以填充到另一个线程中。

在此函数中,我想要对填充的值进行范围调整并使用它们。

但是,我收到一个错误:">无法在myChan(类型接口{}(上范围">

这是我的代码示例:

func myFunc(input string) {
    var myChan interface{}
    switch input {
    case "one":
        myChan = make(chan One)
    case "two":
        myChan = make(chan Two)
    }
    go doStuff(&myChan)
    for _, item := range myChan {
        fmt.Println(item)
    }
}

请帮助我了解如何完成此操作?

编辑:很抱歉我的问题不够清楚。gogoStuff(&myChan(这条线实际上是这样的:

go gocsv.UnmarshalToChan(clientsFile, &myChan)

根据gocsv UnmarshalToChan的文档,"通道必须具有具体类型。这就是为什么我不能有一个 chan 接口{}

我不是 100% 确定我理解这个问题,但看看你写的代码,这就是我解决无法范围问题的方式。这将陷入僵局,因为并非所有内容都已定义......但测距不是问题,也不应该是问题。此外,doStuff代码应该发出何时关闭通道的信号,可以在等待组中传递,使用计数器跟踪等。

package main
import (
    "fmt"
    "log"
)
// One ...
type One struct{}
// Two ...
type Two struct{}
func doStuff(*interface{}) {}
func myFunc(input string) {
    var myChan interface{}
    switch input {
    case "one":
        myChan = make(chan One)
    case "two":
        myChan = make(chan Two)
    }
    // might have to move this line of code into the switch block below...
    // see commented example
    go doStuff(&myChan)
    switch myChan.(type) {
    case chan One:
        // in this way you're not passing an interface{} but a chan or type One or Two
        // go doStuff(&myChan.(chan One))
        for item := range myChan.(chan One) {
            fmt.Println(item)
        }
    case chan Two:
        // go doStuff(&myChan.(chan One))
        for item := range myChan.(chan Two) {
            fmt.Println(item)
        }
    default:
        log.Fatalln("Unknown type entered")
    }
}
func main() {
    myFunc("one")
}

myChan 变量不是通道,类型通道是这样创建的: chan 接口{}

例如,如果您希望通道传递任何类型,则可以使用以下命令:

func main() {
    c := make(chan interface{}, 1)
    go func() {
        for a := range c {
            fmt.Println(a)
        }
    }()
    c <- 21
    c <- "jazz"
    c <- person{"Chet", 88}
    time.Sleep(time.Second)
}
type person struct {
    Name string
    Age int
}

完整示例:https://play.golang.org/p/BJrAHiSAaw

最新更新