The close()
built-in function in Go Language is used to close a particular channel over which a sender and receiver communicate. Channels are closed by the sender once the purpose of communicating over that channel has been achieved. Below is the prototype for the close()
function in GoLang:
func close(c chan<- Type)
If a channel is closed, you can no longer send data on it, but you can still read data from it.
The close()
function takes in only one compulsory parameter as input, which is a channel.
The channel can be of any type.
Below is an example to demonstrate how to use the close()
function:
package main import "fmt" func main() { example := make(chan int, 10) example <- 2 example <- 3 fmt.Println(<-example) close(example) fmt.Println(<-example) result, ok := <- example fmt.Println(result) fmt.Println(ok) }
In the code above, we first create a channel of type int
with the make()
function. Then, we send data on the channel one by one. In this example, the sender and the receiver are the same. We can receive the data from the channel and print it to demonstrate what has been received. It must be noted that despite closing the channel using the close()
function, the data can still be received as it was already sent before the channel closed.
Moreover, we can check whether the channel is closed by using the code:
result, ok := <- example
The result
variable holds the data received on the channel, and the ok
variable holds whether a channel is open. If ok
is false, as it is in this case, it means that the channel is closed. On a closed channel, the value of result
will always have a value of 0 with the same data type as the channel. Since this channel is of type int
, result
will be 0.
RELATED TAGS
CONTRIBUTOR
View all Courses