5

If I want to sleep for 2 seconds I can do the following:

time.Sleep(2 * time.Second)

but when I do:

test := 2
time.Sleep(test * time.Second)

It throws the error

invalid operation: test * time.Second (mismatched types int and time.Duration)

I can fix this by casting test like so: time.Sleep(time.Duration(rand.Intn(5)) * time.Second) but i'm wondering why it is that I need to wrap it in time.Duration when it's a variable and not when it's a raw value?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486

1 Answers1

7

The difference is that you pass a const in the first case of 2 * time.Second and a var in the second case where you declare test := 2. Read this blog post about constants in Go for more details.

Basically, a const literal in the code will be converted to the type that makes sense for the surrounding expression. In the first case 2 * time.Duration this means that the 2 is converted to a time.Duration while in the second case test := 2 the 2 is assigned to the test variable. This means that the type inference happens at that point, giving test the type int which is the default type for the literal 2. If you used the literal 2.0 instead, the test variable would have type float64 instead. However, the expression test * time.Second has the type of test already set and it is different from the type of time.Duration which is why you get that compiler error.

gonutz
  • 5,087
  • 3
  • 22
  • 40