Frage

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?

War es hilfreich?

Lösung

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top