Fraction of Time Sleep Duration in Go
Question:
Why does the following Go code successfully sleep for a fractional duration, while the second one fails?
// Success s := time.Hour / 73.0 fmt.Println("sleeping: ", s) time.Sleep(s) // Failure d := 73.0 s := time.Hour / d fmt.Println("sleeping: ", s) time.Sleep(s) // Error: invalid operation: time.Hour / d (mismatched types time.Duration and float64)
Answer:
The difference lies in the type of the divisor in each line:
To make the second line work, you must convert d to time.Duration:
s := time.Hour / time.Duration(d)
or use one of the following alternative ways:
For values that cannot be represented in time.Duration, such as 73.5, the time.Hour must be converted to float64:
d := 73.5 s := time.Duration(float64(time.Hour) / d)
Further Considerations:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3