SoFunction
Updated on 2025-03-05

Understanding Go channel range through examples

text

Let's look at the following two codes:

Code Snippet 1

func main() {
    channels := make([]chan int, 10) 
    for i := 0; i < 10; i++ {
         go func(ch chan int) {
          ()
          ch <- 1 
         }(channels[i])
    }
    for ch := range channels { 
    ("Routine ", ch, " quit!")
    }
    ("Finish")
}

Guess what result will be printed on it.

Code Snippet 2

func main() {
    ch := make(chan int, 10)
    for i := 0; i < 10; i++ {
        go func() {
            ch <- i
        }()
    }
    for range ch {
        <-ch
    }
    (1111)
}

Guess what result will be printed in Code 2.

Can run it yourself,

Code segment 1 will run normally, Code segment 2 will be deadlocked, Nani, it is different, it is indeed different.

Please note: Code segment 1 channels is a slice type.

Let's summarize

Channel supports for range for traversal, and two details need to be paid attention to.

1. During traversal, if the channel is not closed, a deadlock error will appear.

2. During traversal, if the channel has been closed, the data will be traversed normally. After traversal, the traversal will be exited.

3. For nil channel, both sending and receiving will be blocked.

4. After writing chan, be sure to close chan, otherwise the main coroutine will be blocked when reading.

5. If the channel that has been closed (buffered), if you continue to read the data, you will get a zero value (for int, it is 0). If it is not closed, the data will not be read.

  • In the select statement, except for default, each case operates a channel, either read or write.
  • In the select statement, except for default, the execution order of each case is random.
  • If there is no default statement in the select statement, it will block and wait for any case.
  • The read operation in the select statement must determine whether it is successfully read, and the closed channel can also be read.

Traversing chan and traversing slice types are different.

The above is the detailed content of the deep understanding of the Go channel range using examples. For more information about Go channel range, please follow my other related articles!