去循环频道,但缺少索引

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


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

}


拉莫斯之舞
浏览 159回答 3
3回答

森林海

替代 peterSO 的答案,您可以简单地使用append添加到切片的末尾。

牛魔王的故事

例如,i := 0for result := range results {&nbsp; &nbsp; fmt.Println(result)&nbsp; &nbsp; newresults[i] = result&nbsp; &nbsp; i++}

DIEA

频道没有索引。如果要跟踪计数,请创建自己的计数变量并在 for 循环内递增。另一种方法是创建一个带有索引和任务名称的结构。package mainimport (&nbsp; &nbsp; "fmt")type Task struct {&nbsp; &nbsp; Index int&nbsp; &nbsp; Task&nbsp; string}func main() {&nbsp; &nbsp; tasks := []string{"foo", "bar", "baz"}&nbsp; &nbsp; results := process(tasks)&nbsp; &nbsp; myresults := make([]*Task, 3)&nbsp; &nbsp; for result := range results { // index?&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(result) // I would like to add result to an array of results?&nbsp; &nbsp; &nbsp; &nbsp; // results[index] = result???&nbsp; &nbsp; &nbsp; &nbsp; myresults[result.Index] = result&nbsp; &nbsp; }}func process(tasks []string) <-chan *Task {&nbsp; &nbsp; ch := make(chan *Task)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; for index, task := range tasks {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; t := &Task{Index: index, Task: task}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ch <- t&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // ch <- fmt.Sprintf("processed task %d: %s", index, task)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; close(ch)&nbsp; &nbsp; }()&nbsp; &nbsp; return ch}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go