有没有办法使频道只能接收而不能发送?

huangapple go评论85阅读模式
英文:

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 &lt;-chan string
func RecOnly(c chan string) &lt;-chan string {
	return c
}

func main() {
	a := make(chan string, 123)
	b := RecOnly(a)

	a &lt;- &quot;one&quot;
	a &lt;- &quot;two&quot;
	//b &lt;- &quot;beta&quot; // compile error because of send to receive-only channel
	fmt.Println(&quot;a&quot;, &lt;-a, &quot;b&quot;, &lt;-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 &lt;-chan string = a // or, b := (&lt;-chan string)(a)

    a &lt;- &quot;one&quot;
    a &lt;- &quot;two&quot;
    //b &lt;- &quot;beta&quot; // compile error because of send to receive-only channel
    fmt.Println(&quot;a&quot;, &lt;-a, &quot;b&quot;, &lt;-b)
}

huangapple
  • 本文由 发表于 2016年1月6日 04:42:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/34620860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定