dqsong2010 2018-06-14 15:58
浏览 46
已采纳

在通道上迭代时出现错误“范围内的变量太多”

I'm kind of lost here, I was trying to get a goroutine to add to an array and another goroutine to read from it, which I suspect is somewhat close to what I have below but I need to play around with the wait().

However, I am getting the error prog.go:19:14: too many variables in range, line 19 is for _, v := range c { I can't find an answer for that online, what am I doing or not doing here?

package main

import (
    "fmt"
    //"time"
    "sync"
)

func hello(wg *sync.WaitGroup, s []int, c chan int) {
    for _, v := range s {
        c <- v
    }
    fmt.Println("Finished adding to channel")
    wg.Done()
}

func hello2(wg *sync.WaitGroup, c chan int) {
    fmt.Println("Channel",c)
    for _, v := range c {
        fmt.Println("Received",v)   
    }
    fmt.Println("Finished taking from channel")
    wg.Done()
}

func main() {
    s := []int{1, 2, 3, 4, 5}
    var c = make(chan int, 5)


    var wg sync.WaitGroup
    wg.Add(1)
    go hello(&wg, s, c)
    wg.Wait()
    wg.Add(1)
    go hello2(&wg, c)
    wg.Wait()
    //time.Sleep(1 * time.Second)
    fmt.Println("main function")
}
  • 写回答

1条回答 默认 最新

  • doushi3819244 2018-06-14 16:01
    关注

    When you range over a channel, iterations only produce a single value, the values that were sent on the channel. There is no index or key value like in case of slices or maps.

    So you must use:

    for v := range c {
        fmt.Println("Received", v)   
    }
    

    This is detailed in Spec: For statements:

    If the range expression is a channel, at most one iteration variable is permitted, otherwise there may be up to two.

    And:

    For channels, the iteration values produced are the successive values sent on the channel until the channel is closed. If the channel is nil, the range expression blocks forever.

    And also:

    Function calls on the left are evaluated once per iteration. For each iteration, iteration values are produced as follows if the respective iteration variables are present:

    Range expression                          1st value          2nd value
    
    array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E
    string          s  string type            index    i  int    see below  rune
    map             m  map[K]V                key      k  K      m[k]       V
    channel         c  chan E, <-chan E       element  e  E
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题