如何在循环中为每次迭代重复调用一个函数,得到它的结果然后将结果追加到一个切片中(Golang?

时间:2018-01-09 05:20:16

标签: go

我有ff:

func getSlice(distinctSymbols []string) []symbols {
    // Prepare connection
    stmt1, err := db.Prepare("Select count(*) from stockticker_daily where symbol = $1;")
    checkError(err)
    defer stmt1.Close()
    stmt2, err := db.Prepare("Select date from stockticker_daily where symbol = $1 order by date asc limit 1;")
    checkError(err)
    defer stmt2.Close()
    var symbolsSlice []symbols
    c := make(chan symbols)
    for _, symbol := range distinctSymbols {
        go worker(symbol, stmt1, stmt2, c)
        **symbolsFromChannel := <-c**
        **symbolsSlice = append(symbolsSlice, symbolsFromChannel})**
    }
    return symbolsSlice
}

func worker(symbol string, stmt1 *sql.Stmt, stmt2 *sql.Stmt, symbolsChan chan symbols) {
    var countdp int
    var earliestdate string
    row := stmt1.QueryRow(symbol)
    if err := row.Scan(&countdp); err != nil {
        log.Fatal(err)
    }
    row = stmt2.QueryRow(symbol)
    if err := row.Scan(&earliestdate); err != nil {
        log.Fatal(err)
    }
    symbolsChan <- symbols{symbol, countdp, earliestdate}
}

请看第一个函数,我知道它不会像我预期的那样工作,因为行symbolsFromChannel := <-c将阻塞直到它从通道接收,因此goroutine上的迭代{{1除非删除块,否则将不会继续。这样做的最佳或正确方法是什么?

1 个答案:

答案 0 :(得分:1)

只需循环两次,例如

for _, symbol := range distinctSymbols {
        go worker(symbol, stmt1, stmt2, c)
}
for range distinctSymbols {
        symbolsSlice = append(symbolsSlice, <-c)
}