mofury
mofury

Reputation: 725

What is the preferred approach to do non-blocking select statement with channels in Go

Here's an example with what I want to do

func (zoo *Zoo) feedAnimals(food Food) {
    for animal := range zoo.Animals {
        select {
        case animal.EatChan() <- food:
        default: // Do nothing
        }
    }
}

Animal's EatChan has a small buffer, some times rate of which feedAnimals is called more often than the rate of which some animals can consume the food. When that happens, if I omit default statement in the select block, the select statement will block the for loop and other hungry animals can't get their food. So I'd rather skip the animal that is full (i.e. the channel has reached its capacity.)

However, having an empty default feels weird to me. Is there a better way to do this?

Upvotes: 1

Views: 85

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79566

However, having an empty default feels weird to me.

It shouldn't.

Is there a better way to do this?

No.

You're already doing it properly. The empty default isn't a "do nothing" statement, it's a "don't block" statement. This is just the semantics of how a non-blocking select works.

Upvotes: 2

Related Questions