Sleeping with Fractional Time Durations
In Go, it is possible to sleep for fractional time durations, allowing precise control over the duration of sleep. However, certain limitations must be considered when working with fractions.
Working with Untyped Constants
Consider the following code:
s := time.Hour/73.0 time.Sleep(s)
This code runs successfully and sleeps for the desired fractional duration. Untyped numeric constants can take on different types depending on the context in which they are used. In this case, 73.0 becomes a time.Duration because the right-hand expression requires it.
Failure Due to Mismatched Types
However, the following code fails with a type mismatch error:
d := 73.0 s := time.Hour/d time.Sleep(s)
The reason for this failure is that d is a float64 by default. When attempting to divide time.Hour by d, the types do not match.
Explicit Conversion for Fractions
To make the latter code work, an explicit conversion to time.Duration is necessary:
d := 73.0 s := time.Hour / time.Duration(d) time.Sleep(s)
Alternatively, you can also declare d with the correct type:
d := time.Duration(73.0) s := time.Hour / d time.Sleep(s)
Considerations for Non-Integer Fractions
If the fractional part of the duration cannot be represented as an int64, as is the case with fractions larger than 2^53, you will need to convert time.Hour to float64, perform the division, and then convert the result back to time.Duration:
d := 73.5 s := time.Duration(float64(time.Hour) / d) time.Sleep(s)
The above is the detailed content of How Can I Precisely Sleep for Fractional Time Durations in Go?. For more information, please follow other related articles on the PHP Chinese website!