go - Is there a way to make channels receive-only? -


this works:

// cast chan string <-chan string func reconly(c chan string) <-chan string {     return c }  func main() {     := make(chan string, 123)     b := reconly(a)      <- "one"     <- "two"     //b <- "beta" // compile error because of send receive-only channel     fmt.println("a", <-a, "b", <-b) } 

but there one-liner this, without declaring new function?

you can explicitly define b's type receive-only channel , set value a. cast a receive-only channel. go spec:

a channel may constrained send or receive conversion or assignment.

func main() {     := make(chan string, 123)     var b <-chan string = // or, b := (<-chan string)(a)      <- "one"     <- "two"     //b <- "beta" // compile error because of send receive-only channel     fmt.println("a", <-a, "b", <-b) } 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -