英文:
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 <- 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论