</bugz loading .

invalid operation: n * time.Millisecond (mismatched types int and time.Duration) golang

Error

invalid operation: timeout * time.Millisecond (mismatched types int and time.Duration)
Jump to solution directly ?

Time is not a number

Unlike other languages, in golang, Duration is a type of itself. As int and time.Duration are of two different types, multiplication of them results in an error and crashing of the code.


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.


Operators - golang ref

Multiplying time.Duration with an integer

package main

import (
    "time"
)

func main(){
    timeout := 1000
    
    // Multiplying timeout [ int ] with time.Millisecond [ time.Duration ] 
    // code crashes
    time.Sleep(timeout * time.Millisecond)
    
}
Open in playground

Solution - Converting int to time.Duration

As you cannot multiply time.Duration with int, you can convert int to time.Duration by using time.Duration() function and then multiply them, as shown below 👇🏾.

package main

import (
    "time"
)

func main(){
    timeout := 1000
    
    // converting int to time.Duration by using time.Duration() 
    time.Sleep(time.Duration(timeout) * time.Millisecond)
}
Open in playground

Thank you for reading, happy coding ✌🏾 .