0

I know I can check if a channel is full by trying to send it something like this:

select {
    case ch <- "data":
        // sent
    default:
        // channel full
}

However, is there a way to check if a channel is full without sending anything?

locriacyber
  • 100
  • 4
  • 1
    i wonder why you need that. I dont see why you would not put your alternative logic within the default case. –  Jul 24 '21 at 22:03

1 Answers1

2

cap(ch) returns the buffer capacity for channel ch len(ch) returns the number of unprocessed messages currently in channel ch

So to check if a channel is full, you can do:

cap(ch) == len(ch)
locriacyber
  • 100
  • 4
  • 6
    This is mostly useless, since the main purpose of channels is for concurrent synchronization, and if there is the possibility of any concurrent access, the resulting value is always stale. – JimB Jul 24 '21 at 19:43
  • 1
    I've seen something like this used for "high watermark" checking... `len(ch) == cap(ch)*8/10`. So it can be useful sometimes. Also strictly speaking the dupe is wrong. – rustyx Jul 24 '21 at 21:07