Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 为循环写入通道会跳过迭代_Go_Channel - Fatal编程技术网

Go 为循环写入通道会跳过迭代

Go 为循环写入通道会跳过迭代,go,channel,Go,Channel,我在玩频道。下面的代码包含一个for循环。我不明白为什么程序似乎会跳过每一次迭代,以及为什么最后一个值是0 主程序包 进口( “fmt” “时间” ) func send(c chan int){ 对于i:=1;i

我在玩频道。下面的代码包含一个for循环。我不明白为什么程序似乎会跳过每一次迭代,以及为什么最后一个值是0

主程序包
进口(
“fmt”
“时间”
)
func send(c chan int){
对于i:=1;i<6;i++{
时间。睡眠(时间。秒)

c你的罪魁祸首是
范围c

您不应该在
c
上执行range,而应该使用无限for循环或case语句

func main() {
    c := make(chan int)
    go send(c)
    for {
        d, ok:= <- c
        if !ok{
          break
        }
        fmt.Println(d)
    }
}

因为range从通道中获取一个值,所以正确的代码如下所示

func main() {
    c := make(chan int)
    go send(c)
    for x := range c {
        fmt.Println(x)
    }
}
package main

import (
    "fmt"
    "time"
)

func send(c chan int) {
    for i := 1; i < 6; i++ {
        time.Sleep(time.Second)
        c <- i
    }
    close(c)
}

func main() {
    c := make(chan int)
    go send(c)
    for value := range c {
        fmt.Println(value)
    }
}
主程序包
进口(
“fmt”
“时间”
)
func send(c chan int){
对于i:=1;i<6;i++{
时间。睡眠(时间。秒)

你应该先去看看戈朗之旅。

您同时使用两种不同的阅读方式:

for range c
从c频道读取一次,然后你用
否从频道再次读取。问题是他从频道中提取了两次。从范围中提取一次,打印一次。当频道关闭时,for循环将自动退出,在这种情况下无需选择。这是真的,我只是在更新答案A只需在范围循环中指定值并打印该值即可。是的,就是这样。我以前在文档中看到过,但不知何故,我认为我的代码是等效的。接受这一点是所有基本方面的解释中最完整的。
package main

import (
    "fmt"
    "time"
)

func send(c chan int) {
    for i := 1; i < 6; i++ {
        time.Sleep(time.Second)
        c <- i
    }
    close(c)
}

func main() {
    c := make(chan int)
    go send(c)
    for value := range c {
        fmt.Println(value)
    }
}
for value := range c {
  fmt.Println(value)
}

OR

for {
  select {
  case value, ok := <- c:
    if !ok {
      return
    }
    fmt.Println(value)
  }
}