Explain the use of Go's close function for closing channels?
The use of Go's close function for closing channels are as follows:-
In Go, channels can be closed using the built-in **close**
function. Closing a channel indicates that no more values will be sent on the channel. It is important to note that closing a channel does not delete the values that have already been sent on the channel.
Here's an example of how to close a channel:
ch := make(chan int)
go func() {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
}()
for i := range ch {
fmt.Println(i)
}
In this example, a channel **ch**
of type **int**
is created using the **make**
function. A goroutine is launched which sends integers from 0 to 4 on the channel and then closes the channel using the **close**
function. Finally, the values sent on the channel are received using a **for** **range**
loop until the channel is closed.
It is important to note that attempting to send values on a closed channel will cause a panic. Therefore, it is a good practice to always check whether a channel is closed before attempting to receive from it. This can be done using a multi-valued receive operation with an additional boolean value that indicates whether the channel is closed or not, as shown in the following example:
ch := make(chan int)
go func() {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
}()
for {
i, ok := <-ch
if !ok {
break
}
fmt.Println(i)
}
In this example, the **for**
loop continues to receive values from the channel until the channel is closed, at which point the boolean value **ok**
will be set to **false**
, causing the loop to break.