Home > Backend Development > Golang > How Can I Precisely Sleep for Fractional Time Durations in Go?

How Can I Precisely Sleep for Fractional Time Durations in Go?

Susan Sarandon
Release: 2024-12-05 07:53:13
Original
290 people have browsed it

How Can I Precisely Sleep for Fractional Time Durations in Go?

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

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

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

Alternatively, you can also declare d with the correct type:

d := time.Duration(73.0)
s := time.Hour / d
time.Sleep(s)
Copy after login

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

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!

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