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
Post a Comment