Here is my code
If I use close() inside the func() it is working fine but
if I use close() inside the main but outside of func() it is working but in the end, it is throwing an error.
package main
import "fmt"
func main() {
ch := make(chan int)
go func() {
for i := 0; i < 6; i++ {
// TODO: send iterator over channel
ch <- i
}
close(ch)
}()
// TODO: range over channel to recv values
for v := range ch {
fmt.Println(v)
}
//close(ch) // if I use here
}
So my question is , is it necessary to close(chan) inside the func() if yes why?
and how it works I am a bit confused, I unable to get a proper satisfactory answer.
For channels, the iteration values produced are the successive values sent on the channel until the channel is closed.
The code
for v := range ch {
fmt.Println(v)
}
close(ch)
fails because of a deadlocked loop. The for loop terminates when the channel is closed, but you have not closed it yet.
package main
import "fmt"
func main() {
ch := make(chan int)
go func() {
for i := 0; i < 6; i++ {
// TODO: send iterator over channel
ch <- i
}
}()
// TODO: range over channel to recv values
for v := range ch {
fmt.Println(v)
}
close(ch)
}
0
1
2
3
4
5
fatal error: all goroutines are asleep - deadlock!