Channel stricter types

I would like to start a discussion about channel type safety.

At the moment, you can do this.
This code compiles.

func main()  {
	ch := make(chan bool)

func someFunc(ch chan bool)  {

Ideally, i would be able to describe what someFunc can actually do to my channel.
chan<- bool and <-chan bool are good, but i think we need more.

This could be done in a specific way for channels or adding a more general behavior description.
Something like Rust’s mut comes to mind.


Go is not as safe as Rust: Types in Go don’t communicate mutability or ownership. I think your best bet here is to be idiomatic in your code and naming conventions. If my function creates a channel and that channel doesn’t get returned out of the function, I think it’s easiest to reason about the code if the function that makes it closes it. It’s like the common pattern:

f, err := os.Open("myfile.txt")
if err != nil {
    /* ... */
defer f.Close()

If you intend on passing ownership of the channel to someFunc, then someFunc's documentation should say that it takes ownership of the channel, just like how bytes.NewBuffer takes ownership of the []byte slice it receives and how io.Reader and io.Writer implementations are not allowed to hold onto the []byte slices passed into them according to their documentation.


Bottom line is that you have to check all of your depencies’ source to make sure. You can’t rely on good faith.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.