Anonymous goroutines

Report a typo

The hidden cube() function performs long calculations and returns value in half a second. But your main program has to be finished in two seconds.

Your task is to perform the calculations concurrently and collect all values into the result array.

Write a program in Go
package main

import (
"fmt"
"time"
)

func main() {
// do not modify this block of code
start := time.Now()
defer func() {
if time.Since(start) > time.Second*2 {
fmt.Println(10000)
}
}()

result := [5]int{}
for i := 0; i < 5; i++ {
// run the code in the loop concurrently
func(i int) {
value := cube(i)
// add the value to the result array
}(i)
}
time.Sleep(time.Second)

printResult(result)
}
___

Create a free account to access the full topic