循环播放频道,但缺少索引

When looping over a channel, I would like to get an index - to be able to add to an array.

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
}

For example,

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

Aternatively to peterSO's answer, you can simply use append to add to the end of your slice.

Channels do not have an index. If you want to track the count, create your own count variable and increments within the for loop.

The alternative is to create a struct with a index and the task name.

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
}