Home > Backend Development > Golang > 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?

Barbara Streisand
Release: 2024-12-30 06:05:09
Original
335 people have browsed it

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)
Copy after login

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)
Copy after login

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)
Copy after login

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.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template