Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of creating one-way channels in Go

Tags:

go

channel

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)
like image 703
Ivan Velichko Avatar asked Apr 22 '16 16:04

Ivan Velichko


1 Answers

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.

like image 66
Alexander Trakhimenok Avatar answered Nov 13 '22 11:11

Alexander Trakhimenok