[英]Pass a result from goroutine to a variable inside the loop
At the code below how to assign a result from slowExternalFunction to a proper person ? 在下面的代码中,如何将slowExternalFunction的结果分配给适当的人 ? It can be done via channels and just for clarity I defined that slowExternalFunction returns int .
可以通过渠道完成,为清楚起见,我定义了slowExternalFunction返回int 。
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 https://play.golang.org/p/BRBgtH5ryo
To do it using channels you'll have to refactor your code quite a bit. 要使用渠道来做到这一点,您将不得不对代码进行大量重构。
Smallest change would be to do the assignment in the goroutine: 最小的更改是在goroutine中进行分配:
go func(){
person.WillDieAt = slowExternalFunction(i)
}()
However, to make this work we'd need to make some other changes as well: 但是,要进行这项工作,我们还需要进行其他一些更改:
Here's the complete main
function with the changes: 这是带有更改的完整
main
功能:
func main() {
var persons []*Person
var wg sync.WaitGroup
for i := 0; i <= 100; i++{
person := &Person{}
person.Id = i
person.Name = fastInternalFunction(i)
wg.Add(1)
go func(){
person.WillDieAt = slowExternalFunction(i)
wg.Done()
}()
persons = append(persons,person)
}
wg.Wait()
for _, person := range persons {
fmt.Printf("%v ", person )
}
}
Playground: https://play.golang.org/p/8GWYD29inC 游乐场: https : //play.golang.org/p/8GWYD29inC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.