Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over all the values a channel sends until it is closed in Go

Tags:

go

I am trying to understand how goroutines and channels work. I have a loop sending values to a channel and I'd like to iterate over all the values the channel sends until it is closed.

I have written a simple example here:

package main

import (
    "fmt"
)

func pinger(c chan string) {
    for i := 0; i < 3; i++ {
        c <- "ping"
    }
    close(c)
}

func main() {
    var c chan string = make(chan string)

    go pinger(c)

    opened := true
    var msg string

    for opened {
        msg, opened = <-c
        fmt.Println(msg)
    }
}

This gives the expected result but I'd like to know if there is a shorter way of doing this.

Many thanks for your help

like image 662
Spearfisher Avatar asked Dec 05 '25 19:12

Spearfisher


1 Answers

You can use the range over the channel. The loop will continue until the channel is closed as you want:

package main

import (
    "fmt"
)

func pinger(c chan string) {
    for i := 0; i < 3; i++ {
        c <- "ping"
    }
    close(c)
}

func main() {
    var c chan string = make(chan string)

    go pinger(c)

    for msg := range c {
        fmt.Println(msg)
    }
}
like image 138
Arjan Avatar answered Dec 08 '25 16:12

Arjan