Give conditional case would work for it:
for i := 0; i <= cap(c); i++ {
// how to close the channel after 100 integers are written?
c <- i + 1
// since you send 2 values to channel for each i loop, you need to half of it.
if i == 49 { //if you asking why 49, you have sent one value on bar function. Also to make it perfectly 100 integer in total.
close(ch)
break // terminating the function after the closing channel, it will run in panic because the function still running and keep sending value on channel which was already closed.
}
c <- i + 2
}
Output :
0
1
2
2
3
3
...
50
50
Just give some information about channel, don't use range on channel if you havent sent anything on it...
If you put "i range channel" before you have value on channel, it will not read anything.
Back to again to your code
If you run this code :
func bar() {
c := make(chan int, 200)
c <- 0
go foo(c)
go foo(c) // run in panic
go foo(c) // run in panic
}
It will run in panic, since the channel already closed which mean your channel not accepting any values again.
Take a look at this picture, let say you make a buffered channel with 3 capacity. And you going to close after receiving 2 values to send it will run in panic if you try to send values on it again.
