klin
klin

Reputation: 133

How is this "checking if a channel is closed" working?

var msg = make(chan string)


func checkChannelAndSendMessage() {
    select {
        case <-msg:
            fmt.Print("channel is closed")
        default:
            msg <- "hey"
        }
}

func readMessage() {
  for {
    fmt.Print(<-msg)
  }
}

I have a piece of code which triggers checkChannelAndSendMessage function. I don't understand how this select statement is working to check if a channel is open and then sending messages only if channel is open. Someone please explain it.

Upvotes: 0

Views: 693

Answers (1)

mkopriva
mkopriva

Reputation: 38233

The default: case will be executed if the channel is open and no other goroutine is sending data to that channel. The case <-msg: case will be executed if the channel is closed (returning the zero value of the channel's element type), or it will be executed if some other goroutine is sending data to that channel.

That means that the function by itself is not foolproof, it could very well be used in such a way that it'd print "channel is closed" even while the channel is actually open.

Upvotes: 1

Related Questions