"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does Go's `time.Sleep()` Handle Fractional Durations Differently Based on Constant Type?

Why Does Go's `time.Sleep()` Handle Fractional Durations Differently Based on Constant Type?

Posted on 2025-03-23
Browse:893

Why Does Go's `time.Sleep()` Handle Fractional Durations Differently Based on Constant Type?

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:

  • Success: 73.0 is an untyped numeric constant, which adapts to time.Duration in the expression time.Hour / 73.0.
  • Failure: d is explicitly typed as float64, which cannot be divided by time.Duration.

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:

  • d := time.Duration(73.0)
  • var d time.Duration = 73.0

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:

  • Constants: Constants like time.Hour have a type that cannot be changed, so they cannot be used directly with non-compatible types.
  • Untyped Constants: Untyped constants take on the type of the context they are used in. In the first line, 73.0 adapts to time.Duration.
  • Type Conversion: Explicit type conversions like time.Duration(d) are necessary to ensure compatibility between different types.
Latest tutorial More>

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