去循环通道,但缺少一个索引

时间:2016-02-04 16:55:37

标签: go

循环通道时,我想获得一个索引 - 能够添加到数组中。

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
}

3 个答案:

答案 0 :(得分:2)

例如,

i := 0
for result := range results {
    fmt.Println(result)
    newresults[i] = result
    i++
}

答案 1 :(得分:2)

另外,对于peterSO的答案,您只需使用append添加到切片的末尾即可。

答案 2 :(得分:1)

频道没有索引。如果要跟踪计数,请在for循环中创建自己的计数变量和增量。

另一种方法是创建一个带索引和任务名称的结构。

package main

import (
    "fmt"
)

type Task struct {
    Index int
    Task  string
}

func main() {
    tasks := []string{"foo", "bar", "baz"}
    results := process(tasks)
    myresults := make([]*Task, 3)

    for result := range results { // index?
        fmt.Println(result) // I would like to add result to an array of results?
        // results[index] = result???
        myresults[result.Index] = result
    }
}

func process(tasks []string) <-chan *Task {
    ch := make(chan *Task)
    go func() {
        for index, task := range tasks {
            t := &Task{Index: index, Task: task}
            ch <- t
            // ch <- fmt.Sprintf("processed task %d: %s", index, task)
        }
        close(ch)
    }()
    return ch
}