</bugz loading .
invalid operation: timeout * time.Millisecond (mismatched types int and time.Duration)
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.
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
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 ✌🏾 .