在通道上循环时,我想获得一个索引 - 以便能够添加到数组中。
package main
import (
"fmt"
)
func main() {
tasks := []string{"foo", "bar", "baz"}
results := process(tasks)
for result := range results { // index?
fmt.Println(result) // I would like to add result to an array of results?
// newresults[index] = result???
}
}
func process(tasks []string) <-chan string {
ch := make(chan string)
go func() {
for index, task := range tasks {
ch <- fmt.Sprintf("processed task %d: %s", index, task)
}
close(ch)
}()
return ch
}
森林海
牛魔王的故事
DIEA
相关分类