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

huangapple go评论116阅读模式
英文:

Passing []*io.PipeWriter to io.MultiWriter

问题

我有一堆创建的*io.PipeWriter,想要在一个函数中基于所有这些pipewriter创建一个multiwriter。所以我调用一个函数,类似这样:

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]),它就可以工作了。我该如何使现有的函数能够正常工作,而不必单独传递writers呢?

英文:

I have a bunch of *io.PipeWriter created and would like to make a multiwriter based on all those pipewriters in a function. So I call a function something like

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 &lt;- err
  }
}

I call the method with arguments copyToWriters(reader, errs, []*io.PipeWriter{w1, w2})

But it says
cannot use writers (type []*io.PipeWriter) as type []io.Writer in argument to io.MultiWriter. But
if I change io.MultiWriter(writers) to io.MultiWriter(writers[0],writers[1]) it works. How can I make the existing function work by not having to pass writers separately.

答案1

得分: 5

很抱歉,Golang的类型系统不允许将[]*io.PipeWriter强制转换为[]io.Writer,即使*io.PipeWriter实现了io.Writer接口,因为这需要O(n)的操作(参考链接:https://stackoverflow.com/questions/12753805/type-converting-slices-of-interfaces-in-go/12754757#12754757)。

你能做的最好的办法是创建另一个[]io.Writer并将管道写入器复制到其中:

ws := make([]io.Writer, len(writers))
for i, w := range writers {
    ws[i] = w
}
mw := io.MultiWriter(ws...)

关于为什么需要使用...,请阅读文档(链接:https://golang.org/ref/spec#Passing_arguments_to_..._parameters)。

英文:

Unfortunately, Golang's type system does not allow casting []*io.PipeWriter to []io.Writer even when *io.PipeWriter implements io.Writer since it requires O(n) operation (reference).

The best you can do is create another []io.Writer and copy the pipe writers into it

ws := make([]io.Writer, len(writers))
for i, w := range writers {
	ws[i] = w
}
mw := io.MultiWriter(ws...)

And reason why you nead ..., read the document

huangapple
  • 本文由 发表于 2017年2月20日 10:56:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/42335756.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定