go - Pass a result from goroutine to a variable inside the loop -


at code below how assign result slowexternalfunction proper person? can done via channels , clarity defined slowexternalfunction returns int.

type person struct {     id        int     name      string     willdieat int }  func slowexternalapi(i int) int {     time.sleep(10)     willdieat := + 2040     return willdieat  }  func fastinternalfunction(i int) string {     time.sleep(1)     return fmt.sprintf("ivan %v", i) }  func main() {     var persons []person      := 0; <= 100; i++ {         var person person         person.id =         person.name = fastinternalfunction(i)         go slowexternalapi(i)         person.willdieat = 2050 //should willdieat slowexternalapi         persons = append(persons, person)     }     fmt.printf("%v", persons) } 

https://play.golang.org/p/brbgth5ryo

to using channels you'll have refactor code quite bit.

smallest change assignment in goroutine:

go func(){     person.willdieat = slowexternalfunction(i) }() 

however, make work we'd need make other changes well:

  • use array of pointers can add person before assignment finishes.
  • implement wait group wait goroutines finish before printing results.

here's complete main function changes:

func main() {     var persons []*person     var wg sync.waitgroup      := 0; <= 100; i++{         person := &person{}         person.id =         person.name = fastinternalfunction(i)         wg.add(1)         go func(){             person.willdieat = slowexternalfunction(i)             wg.done()         }()          persons = append(persons,person)     }     wg.wait()     _, person := range persons {         fmt.printf("%v ", person )     } } 

playground: https://play.golang.org/p/8gwyd29inc


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -