DEV Community

Discussion on: Why I’m So Frustrated With Go

Collapse
 
tynor profile image
Tynor Fujimoto • Edited

For instance, try writing a reusable exponential backoff algorithm […] Oh, and you can’t use interface{}.

How about something like this?

func ExponentialBackoff(tries int, unit time.Duration, f func() error) error {
    var err error
    for i := 0; i < tries; i++ {
        err = f()
        if err == nil {
            return nil
        }
        top := int32(math.Exp2(float64(i))) + 2
        n := rand.Int31n(top)
        time.Sleep(time.Duration(n) * unit)
    }
    return err
}

Of course it could be simplified to remove the unit argument if you knew ahead of time which unit you wanted to use.

It could be used like so:

n := 0
f := func() error {
    if n > 5 {
        return nil
    }
    n++
    return errors.New("failed")
}
ExponentialBackoff(10, time.Millisecond, f)