Home >Backend Development >Golang >How to close the channel in golang
In golang, you can use the close() function to close the channel, the syntax is "close(msg_chan)". The channel (chan) is a system resource, so when you do not need to use chan, you need to use the built-in function close to manually close the pipe. Note: If you send data to a closed pipe, the program will panic.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
The channel (chan) in the Go language is also a system resource. Therefore, when we do not need to use chan, we need to manually close the pipe. To close a pipe, you need to use the system's built-in close function.
close() is a built-in function and sets a flag indicating that no more values will be sent to the channel.
close(msg_chan)
Parameters | Description |
---|---|
##msg_chan | The pipe needs to be closed.
ele, ok:= <- MychannelHere, if the value of ok is true, it means that the channel is open and therefore the read operation can be performed. And if the value of is false, it means that the channel is closed, so no read operation will be performed. Explanation
Example of closing channel
//Go程序说明如何 //关闭使用的通道 //range循环和关闭函数 package main import "fmt" func myfun(mychnl chan string) { for v := 0; v < 4; v++ { mychnl <- "nhooo" } close(mychnl) } func main() { //创建通道 c := make(chan string) // 使用 Goroutine go myfun(c) //当ok的值为为true时,表示通道已打开,可以发送或接收数据 //当ok的值设置为false时,表示通道已关闭 for { res, ok := <-c if ok == false { fmt.Println("通道关闭 ", ok) break } fmt.Println("通道打开 ", res, ok) } }
Send data to a closed pipe, program Will pannic
package main import "fmt" func main() { fmt.Println("嗨客网(www.haicoder.net)") ch := make(chan string, 5) ch <- "Hello" ch <- "HaiCoder" ch <- "Python" close(ch) ch <- "Close" }After closing the pipe, we sent a "Close" message using the closed pipe again. After running the program, we saw the program panic, that is , the closed pipe cannot send data again, otherwise, the program will panic. 【Related recommendations:
Go video tutorial, Programming teaching】
The above is the detailed content of How to close the channel in golang. For more information, please follow other related articles on the PHP Chinese website!