문제

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