Mit dem folgenden Code, wie ein Ergebnis von slowExternalFunction zu einem richtigen Person zuweisen? Es kann über Kanäle erfolgen und nur für die Klarheit habe ich definiert, dass slowExternalFunctionint zurückgibt.Übergeben Sie ein Ergebnis von goroutine an eine Variable innerhalb der Schleife
type Person struct {
Id int
Name string
WillDieAt int
}
func slowExternalAPI(i int) int {
time.Sleep(10)
willDieAt := i + 2040
return willDieAt
}
func fastInternalFunction(i int) string {
time.Sleep(1)
return fmt.Sprintf("Ivan %v", i)
}
func main() {
var persons []Person
for i := 0; i <= 100; i++ {
var person Person
person.Id = i
person.Name = fastInternalFunction(i)
go slowExternalAPI(i)
person.WillDieAt = 2050 //should be willDieAt from the slowExternalAPI
persons = append(persons, person)
}
fmt.Printf("%v", persons)
}
https://play.golang.org/p/BRBgtH5ryo