Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read until end of channel in Go

The producer fills up the channel with some values and closes it. On the consumer side I want to add up all the values and leave the loop at the end. My solution looks like:

total := 0
for {
    v, ok := <- ch
    if !ok { break }
    total += v
}

Is there any more elegant way?

like image 806
grep Avatar asked Sep 30 '13 17:09

grep


People also ask

When to close Go channel?

The Channel Closing Principle One general principle of using Go channels is don't close a channel from the receiver side and don't close a channel if the channel has multiple concurrent senders. In other words, we should only close a channel in a sender goroutine if the sender is the only sender of the channel.

Can you read from a closed channel Golang?

We can close a channel in Golang with the help of the close() function. Once a channel is closed, we can't send data to it, though we can still read data from it.

When to use channels in Go?

Go channels are used for communicating between concurrently running functions by sending and receiving a specific element type's data. When we have numerous Goroutines running at the same time, channels are the most convenient way for them to communicate with one another.

Can we use for range through a channel?

The range keyword can also be used on a channel. By doing so, it will iterate over every item thats send on the channel. You can iterate on both buffered and unbuffered channels, but buffered channels need to be closed before iterating over them.


1 Answers

A for/range loop will work, as long as the producer closes the channel.

total := 0

for v := range ch {
    total += v
}

Play: http://play.golang.org/p/cWcA57dnLC

like image 135
lnmx Avatar answered Sep 24 '22 00:09

lnmx