我的程序有一个管道结构,我刚刚实现了一个缓存过滤器,如果已处理的数据版本在缓存中,则该过滤器将直接将内容发送到输出。
func Run(in chan downloader.ReadyDownload) chan CCFile {
out := make(chan CCFile)
processQueue := make(chan downloader.ReadyDownload)
go cache.BypassFilter(in, processQueue, out)
// writes the cached, already processed version to out if it exists
// otherwise redirects the input to processQueue
go process(processQueue, out)
return out
}
问题是我的程序有多个这样的地方,并且许多类型的结构(例如此代码片段中的 ReadyDownload 和 CCFile)正在通过通道传递。他们都实现了这个接口
type ProcessItem interface {
Source() string
Target() string
Key() string
}
所以我的 BypassFilter() 函数签名如下所示:
func (c Cache) BypassFilter(in chan ProcessItem, process chan ProcessItem, bypass chan ProcessItem)
但这会带来以下错误:
cannot use in (type chan downloader.ReadyDownload) as type chan utils.ProcessItem in function argument
尽管ReadyDownload确实实现了ProcessItem。例如,这可以正常工作:
foo := downloader.ReadyDownload{}
var bar utils.ProcessItem
bar = foo
因此,我对 Go 类型和接口的(但)非常有限的理解让我提出了这个问题:它们是事实吗?某物的渠道 and 别的东西,这使得类型不兼容?我应该做什么才能让它发挥作用?假设我有一个 ReadyDownloads 频道。是将数据转发到函数的唯一方法,该函数采用接口通道作为参数,创建一个新的接口通道,将其传递给函数并从 ReadyDownloads 通道读取内容并将它们输入另一个通道?