S
S
SioNica2021-04-21 20:25:12
go
SioNica, 2021-04-21 20:25:12

How to get sequential data from go func()?

Hello!

The code:

var st make([]string, 0)

for _, word := range stro { 

sts, err := au(word , na , la, ge)

st = append(st,  sts)
}

//st processing
with this approach, it processes for a long time.

When I do:

for _, word := range stro { 
func() {
sts, err := au(word , na , la, ge)

st = append(st,  sts)
}()
// st обработка
}

Processes quickly, but the data is not received consistently.

How can I get data sequentially from go func() {}() according to sending word ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2021-04-22
@pav5000

You have the output in an array, with the element numbers corresponding to the output. Therefore, it will be easiest to put them directly in the desired cells.

st := make([]string, len(stro))
  for i := range stro {
    func(i int) {
      word := stro[i]

      sts, err := au(word, na, la, ge)
      if err != nil {
        // .....
      }

      st[i] = sts
    }(i)
  }

Please note that I am passing i as a function parameter, this is important, because the variables that are used in the loop cannot be passed through the closure to the goroutines, because during the loop these variables change their value every iteration.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question