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

这显然有效:


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

}

但是有没有一个单线来做到这一点,而不声明一个新功能?


MYYA
浏览 155回答 1
1回答

aluckdog

您可以将b的类型显式定义为仅接收通道并将其值设置为a。您还可以投射a到仅接收频道。从Go 规范:通道可能被限制为只能发送或只能通过转换或分配接收。func main() {&nbsp; &nbsp; a := make(chan string, 123)&nbsp; &nbsp; var b <-chan string = a // or, b := (<-chan string)(a)&nbsp; &nbsp; a <- "one"&nbsp; &nbsp; a <- "two"&nbsp; &nbsp; //b <- "beta" // compile error because of send to receive-only channel&nbsp; &nbsp; fmt.Println("a", <-a, "b", <-b)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go