0
在下面的代码中,如何将结果从slowExternalFunction分配给合适的人?它可以通过渠道完成,只是为了清晰起见,我定义了slowExternalFunction返回int。将goroutine的结果传递给循环内的变量
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