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
- Q463What does this print? Explain the monotonic clock and time.Time comparison.
- Q464time.Ticker, time.After and timers: what leaks, and what changed in Go 1.23?
- Q466Explain the laws of reflection and settability. What does this print?
- Q467Use reflection to build a simple struct-tag validator (`validate:"required,max=10"`).
- Q468Design a per-client rate limiter for an HTTP API. Implement a token bucket.
- Q469Design a concurrency-safe, generic LRU cache with TTL.