【发布时间】:2021-09-26 15:05:20
【问题描述】:
https://play.golang.org/p/-cHBgiNl0tK
package main
import (
"fmt"
"time"
)
func read(ch ...<-chan int) {
for i := 0; i < len(ch); i++ {
i := i
go func() { fmt.Println(<-ch[i]) }()
}
}
func write(ch ...chan<- int) {
for i := 0; i < len(ch); i++ {
i := i
go func() { ch[i] <- i }()
}
}
func main() {
var maxLen = 10
var ch []chan int
for i := 0; i < maxLen; i++ {
ch = append(ch, make(chan int))
}
read(ch...)
write(ch...)
time.Sleep(10 * time.Second)
}
上面的 sn-p 失败并出现以下错误
./prog.go:28:6: cannot use ch (type []chan int) as type []<-chan int in argument to read
./prog.go:29:7: cannot use ch (type []chan int) as type []chan<- int in argument to write
如何使其与read 和write 函数中的通道方向一起使用?
【问题讨论】:
-
该语言会将双向通道参数转换为定向通道,但不会将双向通道切片转换为定向通道切片。
-
@HymnsForDisco 明白你的意思,但有没有办法可以将比迪通道切片转换为定向通道?
-
使这种转换合法化的现有提案:github.com/golang/go/issues/41695
-
@HymnsForDisco 不错的发现。您应该在答案中添加指向提案的链接。