在下面的代码中,如何将 slowExternalFunction 的结果分配给适当的人?它可以通过渠道来完成,为了清楚起见,我定义 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)
}
答案 0 :(得分:1)
要使用频道进行操作,您必须对代码进行相当多的重构。
最小的变化是在goroutine中进行分配:
go func(){
person.WillDieAt = slowExternalFunction(i)
}()
然而,为了完成这项工作,我们还需要做出其他一些改变:
以下是包含更改的完整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 )
}
}