Receiving Channel Values with "for" + "range"

Posted by yhuang
Public (Editable by Users)

We can use the same looping syntax to iterate over received values in go channels.

Go
Edit
package main

import "fmt"

func main() {

    queue := make(chan string, 2)
    queue <- "one"
    queue <- "two"
    close(queue)

    for elem := range queue {
        fmt.Println(elem)
    }
}