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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀