这显然有效:
// cast chan string to <-chan string func RecOnly(c chan string) <-chan string { return c } func main() { a := make(chan string, 123) b := RecOnly(a) a <- "one" a <- "two" //b <- "beta" // compile error because of send to receive-only channel fmt.Println("a", <-a, "b", <-b) }
但是,如果没有声明新功能,是否有一个单行代码?
您可以将b
类型明确定义为仅接收通道,并将其值设置为a
.您也可以转发a
到仅接收频道.来自Go规范:
频道可能仅限于发送或仅通过转换或分配来接收.
func main() { a := make(chan string, 123) var b <-chan string = a // or, b := (<-chan string)(a) a <- "one" a <- "two" //b <- "beta" // compile error because of send to receive-only channel fmt.Println("a", <-a, "b", <-b) }