Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top