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:
The above is the detailed content of Why Does Go's `time.Sleep()` Handle Fractional Durations Differently Based on Constant Type?. For more information, please follow other related articles on the PHP Chinese website!