英文:
Passing []net.Conn to io.MultiWriter
问题
我有很多net.Conn
,我想实现多个写入器,这样我就可以将数据发送到每个可用的net.Conn
。
我目前的方法是使用io.MultiWriter
。
func route(conn, dst []net.Conn) {
targets := io.MultiWriter(dst[0], dst[1])
_, err := io.Copy(targets, conn)
if err != nil {
log.Println(err)
}
}
但问题是,我必须在io.MultiWriter
中指定每个net.Conn
的索引,这将是一个问题,因为切片的大小是动态的。
当我尝试通过将[]net.Conn
传递给io.MultiWriter
来尝试另一种方法时,像下面的代码一样
func route(conn, dst []net.Conn) {
targets := io.MultiWriter(dst...)
_, err := io.Copy(targets, conn)
if err != nil {
log.Println(err)
}
}
会出现错误"cannot use mirrors (variable of type []net.Conn) as []io.Writer value in argument to io.MultiWriter"
有没有适当的方法来处理这种情况?这样我就可以将net.Conn
切片传递给io.MultiWriter
。
谢谢。
英文:
I have many of net.Conn
and i want to implement multi writer. so i can send data to every available net.Conn
.
My current approach is using io.MultiWriter
.
func route(conn, dst []net.Conn) {
targets := io.MultiWriter(dst[0], dst[1])
_, err := io.Copy(targets, conn)
if err != nil {
log.Println(err)
}
}
but the problem is, i must specify every net.Conn
index in io.MultiWriter
and it will be a problem, because the slice size is dynamic.
when i try another approach by pass the []net.Conn
to io.MultiWriter
, like code below
func route(conn, dst []net.Conn) {
targets := io.MultiWriter(dst...)
_, err := io.Copy(targets, conn)
if err != nil {
log.Println(err)
}
}
there is an error "cannot use mirrors (variable of type []net.Conn) as []io.Writer value in argument to io.MultiWriter"
Is there proper way to handle this case? so i can pass the net.Conn
slice to io.MultiWriter
.
Thank you.
答案1
得分: 1
io.MultiWriter()
的参数类型是 ...io.Writer
,因此你只能传递类型为 []io.Writer
的切片。
所以首先创建一个正确类型的切片,将 net.Conn
的值复制到其中,然后像这样传递它:
ws := make([]io.Writer, len(dst))
for i, c := range dst {
ws[i] = c
}
targets := io.MultiWriter(ws...)
英文:
io.MultiWriter()
has a param of type ...io.Writer
, so you may only pass a slice of type []io.Writer
.
So first create a slice of the proper type, copy the net.Conn
values to it, then pass it like this:
ws := make([]io.Writer, len(dst))
for i, c := range dst {
ws[i] = c
}
targets := io.MultiWriter(ws...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论