{"id":3910,"date":"2020-08-15T22:59:26","date_gmt":"2020-08-15T17:29:26","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=3910"},"modified":"2020-08-15T22:59:39","modified_gmt":"2020-08-15T17:29:39","slug":"for-range-loop-channel-go","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/for-range-loop-channel-go\/","title":{"rendered":"For-range loop for a channel in Go (Golang)"},"content":{"rendered":"\n
For range loop can be used to receive data from the channel until it is closed.\u00a0Do note that for- range loop will keep receiving from the channel the only way for range look to exit is to close the channel.<\/p>\n\n\n\n
Let’s see a program to understand it<\/p>\n\n\n\n
package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tch := make(chan int)\n\tch <- 2\n\tch <- 2\n\tch <- 2\n\tclose(ch)\n\tsum(ch)\n\ttime.Sleep(time.Second * 1)\n}\n\nfunc sum(ch chan int) {\n\tsum := 0\n\tfor val := range ch {\n\t\tsum += val\n\t}\n\tfmt.Printf(\"Sum: %d\\n\", sum)\n}<\/code><\/pre>\n\n\n\nOutput<\/strong><\/p>\n\n\n\nSum: 6<\/code><\/pre>\n\n\n\n\u00a0In the above program,\u00a0 we created a channel.\u00a0\u00a0In the main function the send three values to the channel and after that, we closed the channel. Then we called the sum function and we passed the channel to that function. In the sum function, we did a for range loop over the channel.\u00a0\u00a0 \u00a0After iterating over all the values in the channel the for range loop will exit\u00a0 since the channel is closed<\/p>\n\n\n\n
Now the question which comes to the mind is that what happens if you don't close a channel in the main function.\u00a0 Try commenting the line in which they are closing the channel. Now run the program.\u00a0 It will also\u00a0output\u00a0 deadlock because\u00a0 for range loop will never finish in the sum function<\/p>\n\n\n\n
fatal error: all goroutines are asleep - deadlock!<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"For range loop can be used to receive data from the channel until it is closed.\u00a0Do note that for- range loop will keep receiving from the channel the only way for range…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[3,4],"class_list":["post-3910","post","type-post","status-publish","format-standard","hentry","category-tech","tag-go","tag-golang"],"yoast_head":"\n
For-range loop for a channel in Go (Golang) - Welcome To Golang By Example<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n