英文:
Is there a way to make channels receive-only?
问题
这明显是有效的:
// 将 chan string 转换为 <-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" // 编译错误,因为向只接收的通道发送数据
fmt.Println("a", <-a, "b", <-b)
}
但是,是否有一种一行代码的方法来实现这个,而不需要声明一个新的函数?
英文:
This clearly works:
// 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)
}
but is there a one-liner to do this, without declaring a new function?
答案1
得分: 10
你可以将b
的类型明确定义为只接收的通道,并将其值设置为a
。你也可以将a
强制转换为只接收的通道。根据Go规范:
通过转换或赋值,通道可以被限制为只发送或只接收。
func main() {
a := make(chan string, 123)
var b <-chan string = a // 或者,b := (<-chan string)(a)
a <- "one"
a <- "two"
//b <- "beta" // 编译错误,因为向只接收的通道发送数据
fmt.Println("a", <-a, "b", <-b)
}
英文:
You can explicitly define b
's type as a receive-only channel and set its value to a
. You could also cast a
to a receive-only channel. From the Go spec:
> A channel may be constrained only to send or only to receive by conversion or assignment.
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论