Вопрос

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?

Это было полезно?

Решение

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top