I was the new learning of go version 1.22, in the following code, for i := range ch1; if will throughout all the data in the ch1, if there is already have data, it will printed. but why my output is
0 1
2 3
4 5
6 7
8 9
there are some data missing, index 1, 3, 5, 7, 9 are not output, what is the problem, anyone can help me here? thx!
package main
import "fmt"
func main() {
ch1 := make(chan int, 10)
go func() {
for i := 0; i < 10; i++ {
ch1 <- i
}
close(ch1)
}()
for i := range ch1 {
x, ok := <-ch1
if !ok {
break
}
fmt.Println(i, x)
}
}
the output should be
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
You are reading from the channel twice per iteration:
for i := range ch1
reads a value from the channel.x, ok := <-ch1
reads the next value from the channel.You should decide which one you want to use. Don't mix them.
on 1)
With iteration over a channel there is no index. A range
over a channel will stop the iteration after all items are read from the channel and the channel is closed.
for x := range ch1 {
fmt.Println(x)
}
on 2)
In this case the ok
variable indicates if the channel is empty and closed:
for {
x, ok := <-ch1
if !ok {
break
}
fmt.Println(x)
}