Go: Close a channel

The close function records that no more values will be sent on a channel. (Sending to or closing a closed channel causes a run-time panic.)

After calling close, and after any previously sent values have been received, receive operations will return a zero value without blocking. A multi-valued receive operation additionally returns a boolean indicating whether the value was delivered by a send operation.


ch := make(chan string)
go func() {
    ch <- "Hello!"
    close(ch)
}()
fmt.Println(<-ch)  // prints "Hello!"
fmt.Println(<-ch)  // prints the zero value "" without blocking
fmt.Println(<-ch)  // once again prints ""
v, ok := <-ch      // v is "", ok is false

Read until closed

A for statement with a range clause reads successive values sent on a channel until the channel is closed.


func main() {
    var ch <-chan Sushi = Producer()
    for s := range ch {
        fmt.Println("Consumed", s)
    }
}

func Producer() <-chan Sushi {
    ch := make(chan Sushi)
    go func() {
        ch <- Sushi("海老握り")  // Ebi nigiri
        ch <- Sushi("鮪とろ握り") // Toro nigiri
        close(ch)
    }()
    return ch
}

Comments