💻 Tech
I just learned that you can iterate through array in Go using for range without create variables for index and value. Here’s an example. The code below shows that the second for loop only needs to know how many times to loop through the values.
// uses fan out pattern
func sleepSort(values []int) []int {
ch := make(chan int)
for _, n := range values {
n := n // with Go >= 1.22, you don't need this shadowing
go func() {
time.Sleep(time.Duration(n) * time.Millisecond) // n is an integer, time.Millisecond is time.Duration which is int64
ch <- n
}()
}
var out []int
// loops through values without needing the index
for range values {
n := <-ch
out = append(out, n)
}
return out
}