Time is not a number

yourbasic.org/golang

Why doesn’t this compile?

n := 100
time.Sleep(n * time.Millisecond)
invalid operation: n * time.Millisecond (mismatched types int and time.Duration)

Answer

There is no mixing of numeric types in Go. You can only multiply a time.Duration with

Here are three correct examples.

var n time.Duration = 100
time.Sleep(n * time.Millisecond)
const n = 100
time.Sleep(n * time.Millisecond)
time.Sleep(100 * time.Millisecond)

See Untyped numeric constants with no limits for details about typed and untyped integer and floating point constants and their limits.

Share this page: