Go

What does this print? (time.Duration arithmetic gotchas)

Question 465MediumGo 1.22 to 1.25
retries := 3
// d := retries * time.Second      // compile error: mismatched types int and time.Duration
d := time.Duration(retries) * time.Second
fmt.Println(d)

const n = 3
fmt.Println(n * time.Second)    // untyped constant: OK

timeout := 5
fmt.Println(time.Duration(timeout)) // forgot the unit

fmt.Println(time.Duration(1.5 * float64(time.Second)))
fmt.Println((90 * time.Minute).Hours())

Output:

3s
3s
5ns
1.5s
1.5

time.Duration is an int64 count of nanoseconds. Multiplying a typed int by a Duration doesn't compile; untyped constants convert implicitly. The nasty bug is time.Sleep(time.Duration(cfg.TimeoutSeconds)) or client.Timeout = 5 — that's 5 nanoseconds, which makes every request time out immediately. Config parsing should use time.ParseDuration("5s") or explicit multiplication by a unit. Max Duration is ~292 years; overflow wraps silently.

More on Standard Library, HTTP & Systems Design in Go

All 35 Standard Library, HTTP & Systems Design in Go questions