Reputation: 6709
In Go one can create one-way channels. It's a very convenient feature in case of one want to restrict a set of operations available on the given channel. However, as far as I can see, this feature is useful only for function's arguments and variable's type specification, while creating one-way channels via make
looks strange for me. I've read this question, but it's not about creating read (or write)-only channels in Go, it's about usage in general. So, my question is about use cases of the next code:
writeOnly := make(chan<- string)
readOnly := make(<-chan string)
Upvotes: 8
Views: 1544
Reputation: 6278
Theoretically you can use write only channels for unit testing to ensure for example that your code is not writing more than specific number of times to a channel.
Something like this: http://play.golang.org/p/_TPtvBa1OQ
package main
import (
"fmt"
)
func MyCode(someChannel chan<- string) {
someChannel <- "test1"
fmt.Println("1")
someChannel <- "test2"
fmt.Println("2")
someChannel <- "test3"
fmt.Println("3")
}
func main() {
writeOnly := make(chan<- string, 2) // Make sure the code is writing to channel jsut 2 times
MyCode(writeOnly)
}
But that would be pretty silly technique for unit testing. You're better to create a buffered channel and check its contents.
Upvotes: 5
Reputation: 1746
One of the main reason that people use types (especially in Go) is as a form of documentation. Being able to show that a channel is read-only or write-only, can help the consumer of the API have a better idea of what is going on.
Upvotes: 0