有没有办法让频道只接收?

时间:2016-01-05 20:42:12

标签: go

这显然有效:

// 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)
}

但是在没有声明新功能的情况下是否有单行代码?

1 个答案:

答案 0 :(得分:10)

您可以将b的类型明确定义为仅接收频道,并将其值设置为a。您还可以将a投射到仅接收频道。来自Go spec

  

频道可能仅限于发送或仅通过转换或分配接收。

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)
}