I have two question:
a) Does it make sense to spin up multiple goroutines in a loop for something like calculating a math result?
b) Why doesn't my code work (this is my first attempt at goroutines)? I'm guessing it has something to do with closing the channel.
package main
import (
"fmt"
"math"
"sync"
)
func main() {
input := [][]int{
[]int{10, 9},
[]int{5, 2},
[]int{4, 9},
}
var wg sync.WaitGroup
c := make(chan int)
for _, val := range input {
wg.Add(1)
go func(coordinates []int, c chan int) {
defer wg.Done()
c <- calculateDistance(coordinates[0], coordinates[1])
}(val, c)
}
distances := []int{}
for val := range c {
distances = append(distances, val)
}
wg.Wait()
fmt.Println(distances)
}
func calculateDistance(x int, y int) int {
v := math.Exp2(float64(x)) + math.Exp2(float64(y))
distance := math.Sqrt(v)
return int(distance)
}
Playground link: https://play.golang.org/p/0iJ9hFnb8R