close a channel in go

A channel can be closed by calling the built-in close function. When a channel is closed, no more values can be sent to it, but the remaining values can still be received until the channel is empty.

Here's an example code snippet that demonstrates how to close a channel:

main.go
package main

import "fmt"

func main() {
    ch := make(chan int)

    go func() {
        for i := 1; i <= 5; i++ {
            ch <- i
        }
        close(ch)
    }()

    for {
        value, ok := <-ch
        if !ok {
            break
        }
        fmt.Println(value)
    }
}
291 chars
23 lines

In the above code, we create an integer channel ch and spawn a new goroutine that sends 5 integers to it using a loop. After sending all the integers, the goroutine calls the close function to close the channel.

In the main goroutine, we use an infinite loop to receive values from the channel using the <- operator. The expression value, ok := <-ch receives a value from the channel and stores it in the variable value, and a boolean value indicating whether the channel is closed is stored in the variable ok. If the channel is closed, ok is false and the loop breaks. Otherwise, we print the value received from the channel.

Note that closing a channel is only necessary when the receiver needs to be explicitly told that no more values are coming. If the sender is the only one using the channel, it's not necessary to close it.

gistlibby LogSnag