我创建了一堆*io.PipeWriter
,并希望根据函数中的所有管道编写器创建一个多写器。所以我调用类似
func copyToWriters(reader *bufio.Reader, errs chan error, writers []*io.PipeWriter) {
for _, writer := range writers {
defer writer.Close()
}
mw := io.MultiWriter(writers)
_, err := io.Copy(mw, reader)
if err != nil {
errs <- err
}
}
我用参数copyToWriters(reader, errs, []*io.PipeWriter{w1, w2})
但它说
cannot use writers (type []*io.PipeWriter) as type []io.Writer in argument to io.MultiWriter
。但
如果我将io.MultiWriter(writers)
更改为io.MultiWriter(writers[0],writers[1])
则可行。如何通过不必单独传递编写器来使现有函数工作。
答案 0 :(得分:5)
不幸的是,即使[]*io.PipeWriter
实现[]io.Writer
,Golang的类型系统也不允许将*io.PipeWriter
转换为io.Writer
,因为它需要O(n)操作{{ 3}}
您可以做的最好的事情是创建另一个[]io.Writer
并将管道编写器复制到其中
ws := make([]io.Writer, len(writers))
for i, w := range writers {
ws[i] = w
}
mw := io.MultiWriter(ws...)
为什么你要...
,阅读(reference)