Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

time.Millisecond * int confusion

Tags:

go

In the below example, if the 1000's are both int's (which I think they are) why would the bottom fail to compile?

//works time.Sleep(1000 * time.Millisecond)  //fails var i = 1000 time.Sleep(i * time.Millisecond) 
like image 704
henry.oswald Avatar asked Oct 12 '13 18:10

henry.oswald


2 Answers

Operators

Operators combine operands into expressions.

Comparisons are discussed elsewhere. For other binary operators, the operand types must be identical unless the operation involves shifts or untyped constants. For operations involving constants only, see the section on constant expressions.

Except for shift operations, if one operand is an untyped constant and the other operand is not, the constant is converted to the type of the other operand.

For example, using the "*" (multiplication) operator,

package main  import (     "time" )  func main() {      // works - 1000 is an untyped constant     // which is converted to type time.Duration     time.Sleep(1000 * time.Millisecond)      // fails - v is a variable of type int     // which is not identical to type time.Duration     var v = 1000     // invalid operation: i * time.Millisecond (mismatched types int and time.Duration)     time.Sleep(v * time.Millisecond) } 
like image 136
peterSO Avatar answered Oct 12 '22 18:10

peterSO


You should convert to time.Duration (which underneath is an int64)

var i = 1000 time.Sleep(time.Duration(i) * time.Millisecond) 
like image 39
lcapra Avatar answered Oct 12 '22 18:10

lcapra