gpt4 book ai didi

go - 如何在循环中为每次迭代重复调用一个函数,获取其结果然后将结果附加到一个 slice 中(Golang?

转载 作者:IT王子 更新时间:2023-10-29 02:10:23 24 4
gpt4 key购买 nike

我有 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将阻塞直到它从 channel 接收,因此 goroutine 上的迭代 go worker除非删除 block ,否则不会继续。最好或正确的方法是什么?

最佳答案

只需执行两次循环,例如

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

关于go - 如何在循环中为每次迭代重复调用一个函数,获取其结果然后将结果附加到一个 slice 中(Golang?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48161844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com