Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

golang channal问题请教

package main

import (
    "fmt"
)

func main() {
    resultChan := make(chan int)
    for i := 1; i <= 10; i++ {
        go func(resultChan chan int) {
            //收集结果,比如接口调用的返回的结构,存入channal中
            resultChan <- 1
        }(resultChan)
    }

    //存放resultChan中的值
    var res []int

    /*
    for {
        select {
        case tmp := <-resultChan:
            res = append(res, tmp)
        }
    }
    */
    
    //问题? 如何将resultChan中的值全部收集到res变量中???

    fmt.Println(res)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

按我的理解,我写的代码。。

package main

import (
    "fmt"
    "sync"
)

func main() {
    resultChan := make(chan int)
    var wg sync.WaitGroup
    for i := 1; i <= 10; i++ {
        wg.Add(1)
        go func(resultChan chan int) {
            defer wg.Done()
            //收集结果,比如接口调用的返回的结构,存入channal中
            resultChan <- 1
        }(resultChan)
    }

    //存放resultChan中的值
    var res []int

    go func() {
        wg.Wait()
        close(resultChan)
    }()

    for tmp := range resultChan {
        res = append(res, tmp)
    }

    fmt.Println(res)

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...