Drathier
Drathier

Reputation: 14539

Is there a way to make channels receive-only?

This clearly works:

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

but is there a one-liner to do this, without declaring a new function?

Upvotes: 3

Views: 133

Answers (1)

user142162
user142162

Reputation:

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

Upvotes: 10

Related Questions