我想同時對切片的元素執行操作我正在使用sync/errgroup包來處理并發這是 Go Playground 上的最小復制https://go.dev/play/p/yBCiy8UW_80
1 回答

千巷貓影
TA貢獻1829條經驗 獲得超7個贊
import (
"fmt"
"golang.org/x/sync/errgroup"
)
func main() {
eg := errgroup.Group{}
input := []int{0, 1, 2}
output1 := []int{}
output2 := make([]int, len(input))
for i, n := range input {
eg.Go(func() (err error) {
output1 = append(output1, n+1)
output2[i] = n + 1
return nil
})
}
eg.Wait()
fmt.Printf("with append %+v", output1)
fmt.Println()
fmt.Printf("with make %+v", output2)
}
產出
with append [3 3 3]
with make [0 0 3]
與預期相比[1 2 3]
- 1 回答
- 0 關注
- 155 瀏覽
添加回答
舉報
0/150
提交
取消