将[] * io.PipeWriter传递给io.MultiWriter

时间:2017-02-20 02:56:50

标签: go

我创建了一堆*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])则可行。如何通过不必单独传递编写器来使现有函数工作。

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)