I'm struggling with some code that should be a very simple computation of a duration. The purpose of the code is to generate a random delay, constrained by an upper and lower limit. The reason I'm looking for advise here is that what should be a simple task, has turned into a behemoth of type conversions:
package main
import (
"math/rand"
"time"
)
func main() {
// parameters, hardcoded for illustration purposes only
tMin := float32(1.2)
tMax := float32(2.7)
// intention is approximately this:
// delay := tMin + rand.Float32() * (tMax - tMin)
delay := time.Duration((tMin + rand.Float32() * (tMax - tMin)) * float32(time.Second))
time.Sleep(delay)
}
Questions:
- Apart from rounding errors (which I'm happy to ignore here), does this code have any actual bugs that I missed?
- I know that elegance is in the eye of the beholder, but is there any way to write this more elegantly? In particular, I'd like to reduce the number of required casts, preferably down to zero.